// M5 — Incident forma sa AI klasifikacijom (Vigilo Mobile) · v2
// State machine: entry → analyzing → outcome (lakši | teški) → cluster feedback
// Plus offline/SMS failover stanje (red za sync).
// Princip P2: posmatrač opisuje, sistem klasifikuje.
//
// KLASIFIKACIJA (fix posle Voja + Marko Ivković):
//   TEŠKI = K1 (bezbednost, pritisci, ometanje rada BM, fizičko sprečavanje,
//                 udaljavanje posmatrača, nasilje)
//         = K2 (uticaj na izbornu volju i integritet glasanja: kupovina
//                 glasova, kontrola birača, paralelni spisak, „bugarski voz",
//                 organizovano dovoženje)
//   LAKŠI = K3 (proceduralne sitnice: paravani, telefon na BM, gužva,
//                 nedostatak materijala, sitne procedure BO)
//   K4 (organizovane aktivnosti oko BM: letakovanje, prebrojavanje, kamere
//        ispred BM) → ako su masovne/koordinirane → TEŠKI, inače LAKŠI

const V5 = {
  paper:   'oklch(0.985 0.003 60)',
  surface: 'white',
  ink75:   'oklch(0.972 0.004 60)',
  ink100:  'oklch(0.955 0.005 60)',
  ink150:  'oklch(0.930 0.006 60)',
  ink200:  'oklch(0.900 0.007 60)',
  ink300:  'oklch(0.830 0.008 60)',
  ink400:  'oklch(0.700 0.010 60)',
  ink500:  'oklch(0.580 0.011 60)',
  ink600:  'oklch(0.460 0.012 60)',
  ink700:  'oklch(0.340 0.013 60)',
  ink800:  'oklch(0.240 0.014 60)',
  ink900:  'oklch(0.160 0.015 60)',
  ink950:  'oklch(0.110 0.015 60)',
  red500:  'oklch(0.590 0.215 25)',
  red600:  'oklch(0.520 0.215 25)',
  red700:  'oklch(0.450 0.190 25)',
  red900:  'oklch(0.280 0.110 25)',
  success: 'oklch(0.620 0.155 152)',
  successBg:'oklch(0.960 0.030 152)',
  warning: 'oklch(0.745 0.150 70)',
  warningBg:'oklch(0.970 0.035 80)',
  warningFg:'oklch(0.40 0.15 70)',
  info:    'oklch(0.580 0.155 245)',
  infoBg:  'oklch(0.965 0.025 245)',
  infoFg:  'oklch(0.40 0.155 245)',
  k1:      'oklch(0.59 0.215 25)',
  k2:      'oklch(0.55 0.18 285)',
  k3:      'oklch(0.62 0.155 245)',
  k4:      'oklch(0.7 0.15 70)',
  font:    'Geist, -apple-system, system-ui, sans-serif',
  mono:    '"Geist Mono", ui-monospace, SF Mono, Menlo, monospace',
};

// ── Cluster definitions ──────────────────────────────
const CLUSTERS = {
  K1: {
    code: 'K1',
    color: V5.k1,
    name: 'Bezbednost, pritisci i ometanje rada BM',
    short: 'Bezbednost i pritisci',
    severity: 'teški',
    typical: [
      'Pretnja ili nasilje prema posmatraču ili članu BO',
      'Fizičko sprečavanje rada na BM',
      'Pokušaj udaljavanja posmatrača bez ovlašćenja',
      'Neovlašćeno prisustvo u prostoriji BM',
      'Pritisak na članove BO da odlučuju protivno proceduri',
    ],
  },
  K2: {
    code: 'K2',
    color: V5.k2,
    name: 'Uticaj na izbornu volju i integritet glasanja',
    short: 'Izborna volja',
    severity: 'teški',
    typical: [
      'Kupovina glasova (novac, hrana, paketi za glasanje)',
      'Kontrola birača (fotografisanje listića pred drugima)',
      'Paralelni spisak ispred ili u BM',
      '„Bugarski voz" / lanac listića',
      'Organizovano dovoženje birača autobusima/kombijima',
      'Glasanje istog birača više puta',
    ],
  },
  K3: {
    code: 'K3',
    color: V5.k3,
    name: 'Proceduralne nepravilnosti i izborna dokumentacija',
    short: 'Procedure',
    severity: 'lakši',
    typical: [
      'Paravani ne pokrivaju potpuno',
      'BM nema dovoljno listića / pečata',
      'Telefon u BM (kod birača ili BO)',
      'Gužva u prostoriji, predugačak red',
      'BO nije istakao mandate',
      'Pogrešno popunjavanje zapisnika',
    ],
  },
  K4: {
    code: 'K4',
    color: V5.k4,
    name: 'Organizovane aktivnosti oko biračkog mesta',
    short: 'Aktivnosti oko BM',
    severity: 'mix', // zavisi od organizovanosti
    typical: [
      'Letakovanje ispred BM (manje od 50m)',
      'Kamera ili snimanje prilaza biračima',
      'Lica koja prebrojavaju ulaske',
      'Stranački štandovi u blizini BM',
      'Skupovi/okupljanja u radio glasanja',
    ],
  },
};

// Minimal icons
const I5 = ({ children, size = 18, sw = 1.6, fill = 'none' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={fill} stroke="currentColor" strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>{children}</svg>
);
const Back   = (p) => <I5 {...p}><path d="m15 18-6-6 6-6"/></I5>;
const Cam    = (p) => <I5 {...p}><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></I5>;
const Mic    = (p) => <I5 {...p}><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2M12 19v4M8 23h8"/></I5>;
const Pin    = (p) => <I5 {...p}><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></I5>;
const ChkBig = (p) => <I5 {...p}><path d="M20 6 9 17l-5-5"/></I5>;
const PhoneI = (p) => <I5 {...p}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92z"/></I5>;
const ArrowR = (p) => <I5 {...p}><path d="M5 12h14M12 5l7 7-7 7"/></I5>;
const X      = (p) => <I5 {...p}><path d="M6 6L18 18M18 6L6 18"/></I5>;
const Info   = (p) => <I5 {...p}><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></I5>;
const EyeOff = (p) => <I5 {...p}><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24M1 1l22 22"/></I5>;
const WifiOff= (p) => <I5 {...p}><path d="M1 1l22 22M16.72 11.06A10.94 10.94 0 0 1 19 12.55M5 12.55a10.94 10.94 0 0 1 5.17-2.39M10.71 5.05A16 16 0 0 1 22.58 9M1.42 9a15.91 15.91 0 0 1 4.7-2.88M8.53 16.11a6 6 0 0 1 6.95 0M12 20h.01"/></I5>;
const Wifi   = (p) => <I5 {...p}><path d="M5 13a10 10 0 0 1 14 0M8.5 16.5a5 5 0 0 1 7 0M2 8.82a15 15 0 0 1 20 0M12 20h.01"/></I5>;
const Spark  = (p) => <I5 {...p}><path d="M12 3l1.9 5.6L19.5 10l-5.6 1.9L12 17.5l-1.9-5.6L4.5 10l5.6-1.4z"/></I5>;
const Clock  = (p) => <I5 {...p}><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></I5>;
const Warn   = (p) => <I5 {...p}><path d="M12 9v4M12 17h.01"/><path d="M10.3 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/></I5>;
const Eye    = (p) => <I5 {...p}><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></I5>;

// Tap target
const Tap = ({ children, onClick, style }) => (
  <button onClick={onClick} style={{ background: 'transparent', border: 0, padding: 0, cursor: 'pointer', font: 'inherit', color: 'inherit', WebkitTapHighlightColor: 'transparent', ...style }}>{children}</button>
);

// ═════════════════════════════════════════════════════════════
// AI KLASIFIKACIJA — keyword → cluster
// Vraća { cluster: 'K1'|'K2'|'K3'|'K4', severity: 'teški'|'lakši' }
// ═════════════════════════════════════════════════════════════
function classifyText(t, forceCluster) {
  if (forceCluster) {
    return { cluster: forceCluster, severity: CLUSTERS[forceCluster].severity === 'mix' ? 'teški' : CLUSTERS[forceCluster].severity };
  }
  const txt = t.toLowerCase();

  // K1 — bezbednost, pritisci, ometanje rada
  const k1 = /pretnj|napad|pretukao|fizič|sprečav|sprecav|udar|gurnu|nasilj|udaljav|izbacuj|izbacit|izbacio|otima|zaplen|policij|silov|guran|guranj|sukob|svađ|svadj/i;

  // K2 — uticaj na izbornu volju (kupovina glasova, paralelni spisak, ...)
  const k2 = /kup(uje|ovin|ujem|i\s)\s*glas|nudi\s+nov|novac\s+za\s+glas|paket\s+za\s+glas|paraleln(i|a)\s+(spisak|listu)|bugarski\s+voz|lanac\s+listić|organizovano\s+dovoženje|dovoze\s+(autobus|kombi)|autobus(om|i)\s+dovode|isti\s+birač\s+dva\s+put|dva\s+put(a)?\s+glas|fotografis(anje|ano)\s+listić|sliko?\s+listić|slika\s+listić|kontrol(a|isan)\s+glas/i;

  // K4 — organizovane aktivnosti oko BM (može biti i teški ako masovno)
  const k4 = /letak|delj(en|enje)\s+letak|letakov|kamer(a|e)\s+ispred|snim(a|ano)\s+prilaz|prebrojava\s+ulask|stranač?ki\s+štand|stand\s+ispred|okupljanj|skup\s+ispred|veliki\s+grupa\s+ispred/i;

  // K3 — proceduralne sitnice (lakši)
  const k3 = /paravan|paravan(i|e)|telefon\s+na\s+bm|telefon\s+u\s+bm|telefon\s+kod|gužv|guzv|red\s+predug|nedostat|nemaju\s+listić|pečat|pecat|zapisnik\s+greš|mandat|listić\s+nedov|nema\s+materijal/i;

  if (k1.test(txt)) return { cluster: 'K1', severity: 'teški' };
  if (k2.test(txt)) return { cluster: 'K2', severity: 'teški' };
  if (k4.test(txt)) {
    // K4: ako spomene "organizovano", "masovno", "autobus" → teški
    const heavy4 = /organizov|masovn|autobus|kombi|veliki\s+broj|sistematič?n/i;
    return { cluster: 'K4', severity: heavy4.test(txt) ? 'teški' : 'lakši' };
  }
  if (k3.test(txt)) return { cluster: 'K3', severity: 'lakši' };
  // Default: K3 lakši (procedural)
  return { cluster: 'K3', severity: 'lakši' };
}

// ═════════════════════════════════════════════════════════════
// Atom: Cluster badge
// ═════════════════════════════════════════════════════════════
function ClusterBadge({ cluster, size = 'md' }) {
  const c = CLUSTERS[cluster];
  const padding = size === 'sm' ? '2px 7px' : '3px 9px';
  const fontSize = size === 'sm' ? 10.5 : 12;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding, borderRadius: 5,
      background: c.color, color: cluster === 'K4' ? V5.ink950 : 'white',
      fontFamily: V5.mono, fontSize, fontWeight: 700, letterSpacing: 0.04,
    }}>{c.code}</span>
  );
}

// ═════════════════════════════════════════════════════════════
// SCREEN 1 — Entry
// ═════════════════════════════════════════════════════════════
function ScreenEntry({ text, setText, attachments, toggleAttach, onSubmit, onBack, offline }) {
  const canSend = text.trim().length >= 10;
  return (
    <div style={{ background: V5.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V5.font, color: V5.ink900 }}>
      <div style={{ paddingTop: 56 }} />
      <div style={{ display: 'flex', alignItems: 'center', padding: '8px 12px 4px' }}>
        <Tap onClick={onBack} style={{ width: 40, height: 40, borderRadius: 10, display: 'grid', placeItems: 'center', color: V5.ink700 }}><Back size={20}/></Tap>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 15, fontWeight: 600, color: V5.ink900, letterSpacing: -0.2 }}>Prijavi incident</div>
        <div style={{ width: 40 }} />
      </div>

      {offline && (
        <div style={{ margin: '8px 16px 0', padding: '8px 12px', background: V5.warningBg, border: '1px solid oklch(0.85 0.1 70)', borderRadius: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
          <WifiOff size={14} style={{ color: V5.warningFg }}/>
          <div style={{ fontSize: 11.5, color: V5.warningFg, lineHeight: 1.4 }}>
            <strong style={{ fontWeight: 600 }}>Nema veze.</strong> Prijava se čuva lokalno i šalje čim se veza vrati.
          </div>
        </div>
      )}

      {/* Auto-attached context strip */}
      <div style={{ margin: '8px 16px 0', padding: '10px 12px', background: V5.surface, border: '1px solid ' + V5.ink200, borderRadius: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 30, height: 30, borderRadius: 8, background: V5.ink100, display: 'grid', placeItems: 'center', color: V5.ink700 }}><Pin size={15}/></div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 600, color: V5.ink900 }}>BM 0341/A · OŠ Vladislav Ribnikar</div>
          <div style={{ fontSize: 10.5, color: V5.ink500, fontFamily: V5.mono, marginTop: 1 }}>14:08 · cela smena · Jovana Đurović</div>
        </div>
        <div style={{ fontSize: 10, fontFamily: V5.mono, color: V5.ink400, textTransform: 'uppercase', letterSpacing: 0.06 }}>auto</div>
      </div>

      <div style={{ padding: '14px 16px 0' }}>
        <div style={{ fontSize: 11, fontFamily: V5.mono, color: V5.ink400, textTransform: 'uppercase', letterSpacing: 0.08, marginBottom: 8 }}>Opiši šta vidiš</div>
        <div style={{ marginBottom: 10, padding: '10px 12px', background: V5.infoBg, border: '1px solid oklch(0.88 0.07 245)', borderRadius: 10, display: 'flex', gap: 8, alignItems: 'flex-start' }}>
          <div style={{ marginTop: 1, color: V5.infoFg, flexShrink: 0 }}><Info size={13}/></div>
          <div style={{ fontSize: 11.5, color: V5.infoFg, lineHeight: 1.5 }}>
            Vigilo klasifikuje incident u jedan od <strong style={{ fontWeight: 700 }}>4 klastera</strong>:
            <span style={{ display: 'inline-flex', gap: 4, marginTop: 4, flexWrap: 'wrap' }}>
              <span style={{ fontFamily: V5.mono, fontSize: 9.5, padding: '1px 5px', background: V5.k1, color: 'white', borderRadius: 3, fontWeight: 700 }}>K1 bezbednost</span>
              <span style={{ fontFamily: V5.mono, fontSize: 9.5, padding: '1px 5px', background: V5.k2, color: 'white', borderRadius: 3, fontWeight: 700 }}>K2 integritet</span>
              <span style={{ fontFamily: V5.mono, fontSize: 9.5, padding: '1px 5px', background: V5.k3, color: 'white', borderRadius: 3, fontWeight: 700 }}>K3 procedure</span>
              <span style={{ fontFamily: V5.mono, fontSize: 9.5, padding: '1px 5px', background: V5.k4, color: V5.ink950, borderRadius: 3, fontWeight: 700 }}>K4 aktivnosti</span>
            </span>
          </div>
        </div>
        <textarea
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="Što kraće i konkretnije. Bez procene da li je &bdquo;ozbiljno&ldquo; — sistem klasifikuje."
          style={{
            width: '100%', minHeight: 140, padding: 14, background: V5.surface,
            border: '1px solid ' + V5.ink200, borderRadius: 12, resize: 'none',
            fontFamily: V5.font, fontSize: 15, color: V5.ink900, lineHeight: 1.5,
            outline: 'none', boxSizing: 'border-box',
          }}
        />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 }}>
          <div style={{ fontSize: 11, color: V5.ink500, fontFamily: V5.mono }}>
            {text.length} znakova {canSend ? '· možeš poslati' : '· min 10'}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: V5.ink400 }}>
            <Info size={12}/>
            <span>Privatno do PCC tima</span>
          </div>
        </div>
      </div>

      <div style={{ padding: '16px 16px 0' }}>
        <div style={{ fontSize: 11, fontFamily: V5.mono, color: V5.ink400, textTransform: 'uppercase', letterSpacing: 0.08, marginBottom: 10 }}>Dokazi (opciono)</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
          {[
            { key: 'photo', ic: <Cam size={20}/>, l: 'Slika', n: attachments.photo },
            { key: 'audio', ic: <Mic size={20}/>, l: 'Audio', n: attachments.audio },
            { key: 'gps',   ic: <Pin size={20}/>, l: 'Tačna lokacija', n: attachments.gps ? 1 : 0 },
          ].map(a => (
            <Tap key={a.key} onClick={() => toggleAttach(a.key)} style={{
              padding: '14px 8px', background: a.n ? V5.ink950 : V5.surface,
              color: a.n ? 'white' : V5.ink800,
              border: a.n ? 'none' : '1px solid ' + V5.ink200,
              borderRadius: 12, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
              fontSize: 12, fontWeight: 500, position: 'relative',
            }}>
              {a.ic}
              <span>{a.l}</span>
              {a.n > 0 && a.key !== 'gps' && (
                <span style={{
                  position: 'absolute', top: 8, right: 10,
                  background: V5.warning, color: V5.ink950, fontSize: 10, fontWeight: 700,
                  padding: '1px 5px', borderRadius: 8, fontFamily: V5.mono,
                }}>{a.n}</span>
              )}
            </Tap>
          ))}
        </div>
      </div>

      <div style={{ padding: '18px 20px 0', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
        <div style={{ marginTop: 1, color: V5.ink400 }}><Info size={14}/></div>
        <div style={{ fontSize: 11.5, color: V5.ink500, lineHeight: 1.5 }}>
          Vigilo klasifikuje incident u jedan od <strong style={{ color: V5.ink700 }}>4 klastera</strong> i bira da li ide ka koordinatoru (lakši) ili PCC-u (teški). <strong style={{ color: V5.ink700 }}>Ti ne biraš kategoriju.</strong>
        </div>
      </div>

      <div style={{ flex: 1 }} />

      <div style={{ padding: '14px 16px 38px', background: V5.paper, borderTop: '1px solid ' + V5.ink150 }}>
        <Tap onClick={canSend ? onSubmit : null} style={{
          width: '100%', height: 52,
          background: canSend ? (offline ? V5.warning : V5.ink950) : V5.ink200,
          color: canSend ? (offline ? V5.ink950 : 'white') : V5.ink500,
          borderRadius: 14, fontFamily: V5.font, fontSize: 16, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          cursor: canSend ? 'pointer' : 'default',
        }}>
          {offline ? <><WifiOff size={18} sw={2.4}/>Sačuvaj za slanje</> : <>Pošalji incident <ArrowR size={18} sw={2.4}/></>}
        </Tap>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// SCREEN 2 — Analyzing
// ═════════════════════════════════════════════════════════════
function ScreenAnalyzing({ phase, classification }) {
  const labels = [
    'Šalje se prijava…',
    'Vigilo analizira opis…',
    'Klasifikuje u klaster…',
    classification ? (
      classification.severity === 'teški'
        ? `Klasifikovano kao TEŠKI · ${classification.cluster}`
        : `Klasifikovano kao LAKŠI · ${classification.cluster}`
    ) : '',
  ];
  return (
    <div style={{ background: V5.paper, height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontFamily: V5.font, color: V5.ink900, padding: 40 }}>
      <div style={{ position: 'relative', width: 100, height: 100, marginBottom: 36 }}>
        {[0, 1, 2].map(i => (
          <div key={i} style={{
            position: 'absolute', inset: 0, borderRadius: '50%',
            border: '2px solid ' + V5.ink900, opacity: 0.5,
            animation: `m5pulse 1800ms cubic-bezier(0.2, 0.8, 0.2, 1) ${i * 600}ms infinite`,
          }}/>
        ))}
        <div style={{
          position: 'absolute', inset: 30, borderRadius: 14, background: V5.ink950,
          display: 'grid', placeItems: 'center', color: 'white',
          fontSize: 18, fontWeight: 700, letterSpacing: -0.5,
        }}>V</div>
      </div>
      <div style={{ fontSize: 16, fontWeight: 500, color: V5.ink800, letterSpacing: -0.2, textAlign: 'center', minHeight: 24 }}>
        {labels[phase]}
      </div>
      <div style={{ marginTop: 16, fontSize: 12, color: V5.ink500, textAlign: 'center', lineHeight: 1.5, maxWidth: 280 }}>
        {phase < 3 ? 'Ne zatvaraj aplikaciju. Tvoj izveštaj putuje.' : 'Pripremam sledeći korak…'}
      </div>
      <style>{`@keyframes m5pulse { 0% { transform: scale(0.85); opacity: 0; } 30% { opacity: 0.5; } 100% { transform: scale(1.3); opacity: 0; } }`}</style>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// SCREEN 3a — Outcome lakši
// ═════════════════════════════════════════════════════════════
function ScreenLight({ classification, onClusterFeedback, onReset, summary }) {
  const c = CLUSTERS[classification.cluster];
  return (
    <div style={{ background: V5.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V5.font, color: V5.ink900 }}>
      <div style={{ paddingTop: 70, flex: 1, padding: '70px 20px 16px', display: 'flex', flexDirection: 'column' }}>
        <div style={{
          width: 56, height: 56, borderRadius: 16, background: V5.successBg,
          color: V5.success, display: 'grid', placeItems: 'center', marginBottom: 18,
          boxShadow: '0 0 0 8px oklch(from oklch(0.62 0.155 152) l c h / 0.08)',
        }}><ChkBig size={26} sw={2.6}/></div>

        <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: -0.5, color: V5.ink900, lineHeight: 1.2, marginBottom: 6 }}>
          Incident zabeležen
        </div>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
          <ClusterBadge cluster={classification.cluster}/>
          <span style={{ fontSize: 13, color: V5.ink600 }}>· <strong style={{ color: V5.success }}>LAKŠI</strong> · {c.short}</span>
        </div>
        <div style={{ fontSize: 13.5, color: V5.ink600, lineHeight: 1.5, marginBottom: 20 }}>
          Sistem ga je klasifikovao kao operativni problem koji <strong style={{ color: V5.ink900 }}>ne traži intervenciju PCC-a</strong>. Koordinator je obavešten.
        </div>

        <div style={{ background: V5.surface, border: '1px solid ' + V5.ink200, borderRadius: 12, padding: 14 }}>
          <div style={{ fontSize: 10.5, fontFamily: V5.mono, color: V5.ink400, textTransform: 'uppercase', letterSpacing: 0.08, marginBottom: 10 }}>Šta se dešava dalje</div>
          {[
            { d: V5.success, t: 'Koordinator M. Stojanović obavešten', s: 'Poruka u sledećoj minuti' },
            { d: V5.success, t: 'Zapis u tvojoj istoriji', s: '#INC-1429 · 14:08' },
            { d: V5.ink300,  t: 'Bez poziva od PCC-a', s: 'Možeš nastaviti smenu' },
          ].map((r, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: i === 2 ? 0 : 10 }}>
              <div style={{ marginTop: 4, width: 7, height: 7, borderRadius: '50%', background: r.d, flexShrink: 0 }}/>
              <div>
                <div style={{ fontSize: 13, color: V5.ink900, fontWeight: 500 }}>{r.t}</div>
                <div style={{ fontSize: 11.5, color: V5.ink500, marginTop: 1 }}>{r.s}</div>
              </div>
            </div>
          ))}
        </div>

        {summary && (
          <div style={{ marginTop: 12, padding: '10px 12px', background: V5.ink75, borderRadius: 10, borderLeft: '3px solid ' + V5.ink300 }}>
            <div style={{ fontSize: 10.5, fontFamily: V5.mono, color: V5.ink500, textTransform: 'uppercase', letterSpacing: 0.06, marginBottom: 3 }}>Tvoj opis</div>
            <div style={{ fontSize: 12.5, color: V5.ink700, lineHeight: 1.45 }}>„{summary}“</div>
          </div>
        )}

        <div style={{ flex: 1 }} />
      </div>

      <div style={{ padding: '10px 16px 36px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <Tap onClick={onClusterFeedback} style={{
          width: '100%', height: 48, background: V5.surface, border: '1px solid ' + V5.ink200, color: V5.ink900,
          borderRadius: 12, fontFamily: V5.font, fontSize: 14, fontWeight: 500,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <Spark size={15}/>Šta još da pratim u ovom klasteru
        </Tap>
        <Tap onClick={onReset} style={{
          width: '100%', height: 48, background: V5.ink950, color: 'white',
          borderRadius: 12, fontFamily: V5.font, fontSize: 15, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>Nazad na početni</Tap>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// SCREEN 3b — Outcome teški (URGENT · PCC alarm)
// ═════════════════════════════════════════════════════════════
function ScreenHeavy({ classification, onClusterFeedback, onReset }) {
  const [elapsed, setElapsed] = React.useState(0);
  const [callStatus, setCallStatus] = React.useState('queued'); // queued → connecting → ringing
  React.useEffect(() => {
    const t = setTimeout(() => setElapsed(s => s + 1), 1000);
    return () => clearTimeout(t);
  }, [elapsed]);
  React.useEffect(() => {
    const t1 = setTimeout(() => setCallStatus('connecting'), 4000);
    const t2 = setTimeout(() => setCallStatus('ringing'), 9000);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);
  const mm = String(Math.floor(elapsed / 60)).padStart(2, '0');
  const ss = String(elapsed % 60).padStart(2, '0');

  const c = CLUSTERS[classification.cluster];

  return (
    <div style={{
      background: V5.red900, height: '100%', display: 'flex', flexDirection: 'column',
      fontFamily: V5.font, color: 'white',
      backgroundImage: 'radial-gradient(circle at 50% 0%, oklch(0.45 0.19 25), oklch(0.22 0.09 25))',
    }}>
      <div style={{ paddingTop: 56 }} />

      {/* SOS pulse bar at top */}
      <div style={{
        margin: '8px 16px 0', padding: '6px 12px',
        background: 'oklch(0 0 0 / 0.25)', borderRadius: 999,
        display: 'flex', alignItems: 'center', gap: 8,
        fontSize: 11, fontFamily: V5.mono, color: 'oklch(0.95 0.07 25)',
        textTransform: 'uppercase', letterSpacing: 0.1, fontWeight: 600,
        alignSelf: 'center',
      }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'oklch(0.85 0.15 25)', animation: 'm5dot 1.2s ease-in-out infinite' }}/>
        Crveni telefon · PCC alarm
      </div>

      {/* Pulsing phone icon */}
      <div style={{ padding: '20px 24px 0', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <div style={{ position: 'relative', width: 96, height: 96, marginBottom: 14 }}>
          {[0, 1, 2].map(i => (
            <div key={i} style={{
              position: 'absolute', inset: 0, borderRadius: '50%',
              border: '2px solid white', opacity: 0.4,
              animation: `m5ring 1400ms cubic-bezier(0.2, 0.8, 0.2, 1) ${i * 466}ms infinite`,
            }}/>
          ))}
          <div style={{
            position: 'absolute', inset: 22, borderRadius: '50%', background: 'white',
            color: V5.red600, display: 'grid', placeItems: 'center',
            boxShadow: '0 8px 20px oklch(0 0 0 / 0.3)',
            transform: callStatus === 'ringing' ? 'rotate(-4deg)' : 'none',
            animation: callStatus === 'ringing' ? 'm5shake 0.5s ease-in-out infinite' : 'none',
          }}><PhoneI size={28} sw={2.4}/></div>
        </div>

        {/* Cluster classification */}
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
          <ClusterBadge cluster={classification.cluster}/>
          <span style={{ fontSize: 11.5, color: 'oklch(1 0 0 / 0.75)', fontFamily: V5.mono, textTransform: 'uppercase', letterSpacing: 0.08 }}>
            TEŠKI · {c.short}
          </span>
        </div>

        <div style={{ fontSize: 26, fontWeight: 600, letterSpacing: -0.4, lineHeight: 1.1, textAlign: 'center', marginBottom: 6 }}>
          {callStatus === 'queued' ? <>PCC obrađuje<br/>tvoju prijavu</>
            : callStatus === 'connecting' ? <>PCC operater<br/>te poziva</>
            : <>📞 Stiže poziv —<br/>ostani na vezi</>}
        </div>
        <div style={{ fontSize: 13.5, opacity: 0.78, textAlign: 'center', lineHeight: 1.5, maxWidth: 300 }}>
          Sistem je klasifikovao kao TEŠKI incident i alarmirao pravni tim, koordinatora i šefa misije.
        </div>
      </div>

      {/* Call status card */}
      <div style={{ margin: '20px 16px 0', padding: 14, background: 'oklch(1 0 0 / 0.08)', borderRadius: 14, border: '1px solid oklch(1 0 0 / 0.1)' }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 10.5, fontFamily: V5.mono, textTransform: 'uppercase', letterSpacing: 0.06, opacity: 0.6, marginBottom: 4 }}>Status poziva</div>
            <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: -0.3, lineHeight: 1.1 }}>
              {callStatus === 'queued' && '3. u redu'}
              {callStatus === 'connecting' && 'Operater dolazi'}
              {callStatus === 'ringing' && 'Zvoni telefon'}
            </div>
            <div style={{ fontSize: 11.5, opacity: 0.65, marginTop: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'oklch(0.85 0.15 60)', animation: 'm5dot 1.4s ease-in-out infinite' }}/>
              <span>{callStatus === 'queued' ? '2 operatera dostupna · ~2–3 min' : callStatus === 'connecting' ? 'B. Janković · PCC BG' : 'B. Janković poziva'}</span>
            </div>
          </div>
          <div style={{ textAlign: 'right', paddingLeft: 12, borderLeft: '1px solid oklch(1 0 0 / 0.12)' }}>
            <div style={{ fontSize: 10.5, fontFamily: V5.mono, textTransform: 'uppercase', letterSpacing: 0.06, opacity: 0.55, marginBottom: 4 }}>Otvoreno</div>
            <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: -0.5, fontFamily: V5.mono, fontVariantNumeric: 'tabular-nums' }}>{mm}:{ss}</div>
          </div>
        </div>
      </div>

      {/* Instructions */}
      <div style={{ margin: '14px 16px 0', padding: '14px 16px', background: V5.ink950, borderRadius: 14 }}>
        <div style={{ fontSize: 10.5, fontFamily: V5.mono, textTransform: 'uppercase', letterSpacing: 0.08, color: 'oklch(0.7 0.005 60)', marginBottom: 10 }}>Dok čekaš poziv</div>
        {[
          { ic: <EyeOff size={14}/>, t: 'Ne otkrivaj snimak',   s: 'Ne pokazuj telefon ni jednoj osobi.' },
          { ic: <X size={16}/>,       t: 'Ne ulazi u sukob',     s: 'Ostani gde si, ne odgovaraj na provokacije.' },
          { ic: <PhoneI size={14}/>,  t: 'Ne zovi sam',           s: 'Sistem je obavestio pravni tim.' },
        ].map((r, i, arr) => (
          <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: i === arr.length - 1 ? 0 : 10 }}>
            <div style={{ marginTop: 2, color: 'oklch(0.85 0.15 60)' }}>{r.ic}</div>
            <div>
              <div style={{ fontSize: 13, color: 'white', fontWeight: 600 }}>{r.t}</div>
              <div style={{ fontSize: 11.5, color: 'oklch(0.75 0.005 60)', lineHeight: 1.4, marginTop: 1 }}>{r.s}</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ flex: 1 }} />

      <div style={{ padding: '10px 16px 36px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <Tap onClick={onClusterFeedback} style={{
          width: '100%', height: 42, background: 'oklch(1 0 0 / 0.1)',
          border: '1px solid oklch(1 0 0 / 0.15)',
          color: 'white', fontSize: 12.5, fontWeight: 500,
          borderRadius: 11,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>
          <Spark size={14}/>Šta još da pratim u {classification.cluster}
        </Tap>
        <Tap style={{
          width: '100%', height: 52, background: 'white', color: V5.red700,
          borderRadius: 14, fontFamily: V5.font, fontSize: 16, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <PhoneI size={18} sw={2.4}/> Spreman/spremna za poziv
        </Tap>
        <Tap onClick={onReset} style={{
          width: '100%', height: 32, background: 'transparent', color: 'oklch(1 0 0 / 0.55)',
          fontFamily: V5.font, fontSize: 12,
          textDecoration: 'underline', textUnderlineOffset: 3,
        }}>Ja sam u redu — otkaži poziv</Tap>
      </div>

      <style>{`
        @keyframes m5ring { 0% { transform: scale(0.85); opacity: 0; } 30% { opacity: 0.4; } 100% { transform: scale(1.7); opacity: 0; } }
        @keyframes m5dot { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
        @keyframes m5shake { 0%, 100% { transform: rotate(-4deg); } 50% { transform: rotate(4deg); } }
      `}</style>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// SCREEN 4 — Cluster feedback (šta još da pratim)
// ═════════════════════════════════════════════════════════════
function ScreenClusterFeedback({ classification, onBack, onReset }) {
  const c = CLUSTERS[classification.cluster];
  const isHeavy = classification.severity === 'teški';
  return (
    <div style={{ background: V5.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V5.font, color: V5.ink900 }}>
      <div style={{ paddingTop: 56 }} />
      <div style={{ display: 'flex', alignItems: 'center', padding: '8px 12px 4px' }}>
        <Tap onClick={onBack} style={{ width: 40, height: 40, borderRadius: 10, display: 'grid', placeItems: 'center', color: V5.ink700 }}><Back size={20}/></Tap>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 14, fontWeight: 600, color: V5.ink900 }}>Klaster {c.code}</div>
        <div style={{ width: 40 }} />
      </div>

      <div style={{ padding: '12px 20px 0', flex: 1, overflow: 'auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
          <ClusterBadge cluster={c.code}/>
          <span style={{ fontSize: 11.5, color: V5.ink500, fontFamily: V5.mono, textTransform: 'uppercase', letterSpacing: 0.08 }}>{isHeavy ? 'TEŠKI' : 'LAKŠI'}</span>
        </div>
        <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: -0.4, color: V5.ink950, lineHeight: 1.2, marginBottom: 10 }}>{c.name}</div>

        <div style={{ padding: '14px 16px', background: V5.infoBg, border: '1px solid oklch(0.88 0.07 245)', borderRadius: 12, marginBottom: 18, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <div style={{ marginTop: 1, color: V5.infoFg }}><Spark size={15}/></div>
          <div style={{ fontSize: 13, color: V5.infoFg, lineHeight: 1.5 }}>
            <strong style={{ fontWeight: 600 }}>Prati i ostale incidente iz ovog klastera.</strong> Istorijski se javljaju zajedno — ako vidiš još nešto od dole navedenih, prijavi posebno. Sistem će ih povezati u zajednički obrazac.
          </div>
        </div>

        <div style={{ fontSize: 10.5, fontFamily: V5.mono, color: V5.ink400, textTransform: 'uppercase', letterSpacing: 0.08, marginBottom: 10 }}>Tipični incidenti u {c.code}</div>
        <div style={{ background: V5.surface, border: '1px solid ' + V5.ink200, borderRadius: 12, overflow: 'hidden', marginBottom: 16 }}>
          {c.typical.map((it, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'flex-start', gap: 12,
              padding: '12px 14px',
              borderTop: i === 0 ? '0' : '1px solid ' + V5.ink150,
            }}>
              <div style={{ flexShrink: 0, width: 6, height: 6, borderRadius: '50%', background: c.color, marginTop: 7 }}/>
              <div style={{ fontSize: 13.5, color: V5.ink800, lineHeight: 1.45 }}>{it}</div>
            </div>
          ))}
        </div>

        <div style={{ padding: '12px 14px', background: V5.ink75, border: '1px solid ' + V5.ink200, borderRadius: 12, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <div style={{ marginTop: 1, color: V5.ink500 }}><Eye size={14}/></div>
          <div style={{ fontSize: 12, color: V5.ink600, lineHeight: 1.5 }}>
            Ako vidiš ovakvo nešto u sledećih <strong style={{ color: V5.ink900 }}>30 minuta</strong> u svom BM ili u okolini — prijavi odmah. Slučajevi povezani u klaster lakše prolaze sample analizu.
          </div>
        </div>
      </div>

      <div style={{ padding: '12px 16px 36px', display: 'flex', gap: 8 }}>
        <Tap onClick={onBack} style={{
          flex: 1, height: 48, background: V5.surface, border: '1px solid ' + V5.ink200, color: V5.ink800,
          borderRadius: 12, fontFamily: V5.font, fontSize: 14, fontWeight: 500,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>Nazad</Tap>
        <Tap onClick={onReset} style={{
          flex: 1.5, height: 48, background: V5.ink950, color: 'white',
          borderRadius: 12, fontFamily: V5.font, fontSize: 15, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>Razumem · početni</Tap>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// SCREEN 5 — Offline / SMS failover (red za sync)
// ═════════════════════════════════════════════════════════════
function ScreenOfflineQueue({ onReset, items }) {
  return (
    <div style={{ background: V5.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V5.font, color: V5.ink900 }}>
      <div style={{ paddingTop: 56 }} />
      <div style={{ display: 'flex', alignItems: 'center', padding: '8px 12px 4px' }}>
        <Tap onClick={onReset} style={{ width: 40, height: 40, borderRadius: 10, display: 'grid', placeItems: 'center', color: V5.ink700 }}><Back size={20}/></Tap>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 14, fontWeight: 600, color: V5.ink900 }}>Red za sync</div>
        <div style={{ width: 40 }} />
      </div>

      <div style={{ margin: '12px 16px 0', padding: '12px 14px', background: V5.warningBg, border: '1px solid oklch(0.85 0.1 70)', borderRadius: 12, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
        <div style={{ marginTop: 1, color: V5.warningFg }}><WifiOff size={15}/></div>
        <div style={{ fontSize: 12.5, color: V5.warningFg, lineHeight: 1.45 }}>
          <strong style={{ fontWeight: 600, display: 'block', fontSize: 13.5, marginBottom: 2 }}>Nema veze sa serverom.</strong>
          Tvoji incidenti se čuvaju lokalno na telefonu i šalju se automatski čim se veza vrati. SMS failover je aktivan za <strong style={{ fontWeight: 600 }}>teške</strong> prijave.
        </div>
      </div>

      <div style={{ padding: '20px 16px 8px' }}>
        <div style={{ fontSize: 10.5, fontFamily: V5.mono, color: V5.ink400, textTransform: 'uppercase', letterSpacing: 0.08, marginBottom: 10, display: 'flex', justifyContent: 'space-between' }}>
          <span>{items.length} prijava u redu</span>
          <span>poslednji pokušaj 14:09</span>
        </div>

        <div style={{ background: V5.surface, border: '1px solid ' + V5.ink200, borderRadius: 12, overflow: 'hidden' }}>
          {items.map((it, i) => (
            <div key={i} style={{
              padding: '12px 14px', borderTop: i === 0 ? 0 : '1px solid ' + V5.ink150,
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <div style={{
                width: 30, height: 30, borderRadius: 8,
                background: it.severity === 'teški' ? V5.red500 : V5.ink100,
                color: it.severity === 'teški' ? 'white' : V5.ink700,
                display: 'grid', placeItems: 'center', flexShrink: 0,
              }}>
                {it.severity === 'teški' ? <PhoneI size={14}/> : <Clock size={14}/>}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
                  <ClusterBadge cluster={it.cluster} size="sm"/>
                  <span style={{ fontSize: 10.5, fontFamily: V5.mono, color: V5.ink500, textTransform: 'uppercase', letterSpacing: 0.06, fontWeight: 600 }}>
                    {it.severity === 'teški' ? 'teški · SMS' : 'lakši · čeka'}
                  </span>
                </div>
                <div style={{ fontSize: 12.5, color: V5.ink900, lineHeight: 1.4, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.preview}</div>
                <div style={{ fontSize: 10.5, color: V5.ink500, fontFamily: V5.mono, marginTop: 2 }}>{it.time} · {it.size}</div>
              </div>
              <div style={{ fontSize: 10.5, fontFamily: V5.mono, color: it.severity === 'teški' ? V5.success : V5.ink400, textTransform: 'uppercase', letterSpacing: 0.04 }}>
                {it.severity === 'teški' ? '✓ SMS' : 'čeka'}
              </div>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 12, padding: '10px 12px', background: V5.infoBg, border: '1px solid oklch(0.88 0.07 245)', borderRadius: 10, display: 'flex', gap: 8, alignItems: 'flex-start' }}>
          <Spark size={13} style={{ color: V5.infoFg, marginTop: 2, flexShrink: 0 }}/>
          <div style={{ fontSize: 11.5, color: V5.infoFg, lineHeight: 1.5 }}>
            <strong style={{ fontWeight: 600 }}>Teški incidenti se šalju SMS-om</strong> čim aplikacija detektuje signal — i bez podataka. Lakši čekaju da se vrati internet.
          </div>
        </div>
      </div>

      <div style={{ flex: 1 }}/>

      <div style={{ padding: '12px 16px 36px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <Tap style={{
          width: '100%', height: 48, background: V5.surface, border: '1px solid ' + V5.ink200, color: V5.ink800,
          borderRadius: 12, fontFamily: V5.font, fontSize: 14, fontWeight: 500,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}><Wifi size={15}/>Pokušaj ponovo</Tap>
        <Tap onClick={onReset} style={{
          width: '100%', height: 48, background: V5.ink950, color: 'white',
          borderRadius: 12, fontFamily: V5.font, fontSize: 15, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>Nazad na početni</Tap>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// FLOW STATE MACHINE
// ═════════════════════════════════════════════════════════════
function IncidentFlow({ tweaks, initialText = '' }) {
  const [state, setState] = React.useState('entry');
  const [text, setText] = React.useState(initialText);
  const [attachments, setAttachments] = React.useState({ photo: 0, audio: 0, gps: false });
  const [classifyPhase, setClassifyPhase] = React.useState(0);
  const [classification, setClassification] = React.useState(null);

  // Tweaks-driven state jump
  React.useEffect(() => {
    if (tweaks.view && tweaks.view !== 'auto') {
      const force = tweaks.forceCluster && tweaks.forceCluster !== 'auto' ? tweaks.forceCluster : null;
      if (tweaks.view === 'entry')       { setState('entry'); }
      else if (tweaks.view === 'offline-entry') { setState('entry'); }
      else if (tweaks.view === 'analyzing') { setState('analyzing'); setClassifyPhase(2); }
      else if (tweaks.view === 'lakši')    { setClassification({ cluster: force || 'K3', severity: 'lakši' }); setState('light'); }
      else if (tweaks.view === 'teški')    { setClassification({ cluster: force || 'K2', severity: 'teški' }); setState('heavy'); }
      else if (tweaks.view === 'cluster-feedback') { setClassification({ cluster: force || 'K2', severity: 'teški' }); setState('cluster_feedback'); }
      else if (tweaks.view === 'offline')  { setState('offline_queue'); }
    }
  }, [tweaks.view, tweaks.forceCluster]);

  const reset = () => {
    setState('entry');
    setText(initialText || '');
    setAttachments({ photo: 0, audio: 0, gps: false });
    setClassifyPhase(0);
    setClassification(null);
  };

  const toggleAttach = (key) => {
    setAttachments(a => {
      if (key === 'gps') return { ...a, gps: !a.gps };
      return { ...a, [key]: a[key] >= 2 ? 0 : a[key] + 1 };
    });
  };

  const submit = () => {
    if (tweaks.offline) {
      setState('offline_queue');
      return;
    }
    setState('analyzing');
    setClassifyPhase(0);
    setClassification(null);
    const d = (tweaks.classifyDuration || 2.5) * 1000;
    const force = tweaks.forceCluster && tweaks.forceCluster !== 'auto' ? tweaks.forceCluster : null;
    setTimeout(() => setClassifyPhase(1), d * 0.25);
    setTimeout(() => setClassifyPhase(2), d * 0.55);
    setTimeout(() => {
      const c = classifyText(text, force);
      setClassification(c);
      setClassifyPhase(3);
    }, d * 0.85);
    setTimeout(() => {
      const c = classifyText(text, force);
      setState(c.severity === 'teški' ? 'heavy' : 'light');
    }, d);
  };

  const QUEUE_ITEMS = [
    { cluster: 'K2', severity: 'teški', preview: 'Vidim kako neko deli novac u plavom kombiju ispred BM…', time: '14:07', size: '1.2 KB + 1 slika' },
    { cluster: 'K3', severity: 'lakši', preview: 'Paravani u kabini 2 ne pokrivaju do kraja…', time: '13:48', size: '0.4 KB' },
    { cluster: 'K1', severity: 'teški', preview: 'Predsednik BO je uperio prstom na mene i rekao da napustim prostoriju…', time: '13:32', size: '0.8 KB + audio' },
  ];

  if (state === 'entry')             return <ScreenEntry text={text} setText={setText} attachments={attachments} toggleAttach={toggleAttach} onSubmit={submit} onBack={reset} offline={tweaks.offline}/>;
  if (state === 'analyzing')         return <ScreenAnalyzing phase={classifyPhase} classification={classification}/>;
  if (state === 'light')             return <ScreenLight classification={classification} onClusterFeedback={() => setState('cluster_feedback')} onReset={reset} summary={text}/>;
  if (state === 'heavy')             return <ScreenHeavy classification={classification} onClusterFeedback={() => setState('cluster_feedback')} onReset={reset}/>;
  if (state === 'cluster_feedback')  return <ScreenClusterFeedback classification={classification} onBack={() => setState(classification.severity === 'teški' ? 'heavy' : 'light')} onReset={reset}/>;
  if (state === 'offline_queue')     return <ScreenOfflineQueue onReset={reset} items={QUEUE_ITEMS}/>;
  return null;
}

Object.assign(window, { IncidentFlow });
