// M8 — OCR slikanje zapisnika (Vigilo Mobile)
// Stanja: instructions → camera → processing → results → submitted
// Princip: OCR čita brojeve, posmatrač POTVRĐUJE — ako se ne slaže, manuelni unos.
// Soft warnings ostaju: razlika sa preposlednjim izveštajem se ističe.

const V8 = {
  paper:   'oklch(0.985 0.003 60)',
  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)',
  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)',
  info:    'oklch(0.580 0.155 245)',
  infoBg:  'oklch(0.965 0.025 245)',
  font:    'Geist, -apple-system, system-ui, sans-serif',
  mono:    '"Geist Mono", ui-monospace, SF Mono, Menlo, monospace',
};

const I8 = ({ 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 Back8   = (p) => <I8 {...p}><path d="m15 18-6-6 6-6"/></I8>;
const X8      = (p) => <I8 {...p}><path d="M18 6 6 18M6 6l12 12"/></I8>;
const Cam8    = (p) => <I8 {...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"/></I8>;
const Bolt    = (p) => <I8 {...p}><path d="M13 2 3 14h9l-1 8 10-12h-9l1-8z"/></I8>;
const Grid8   = (p) => <I8 {...p}><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></I8>;
const Sun8    = (p) => <I8 {...p}><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></I8>;
const Chk8    = (p) => <I8 {...p}><path d="M20 6 9 17l-5-5"/></I8>;
const Warn8   = (p) => <I8 {...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"/></I8>;
const Pencil8 = (p) => <I8 {...p}><path d="M12 20h9M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z"/></I8>;
const Arrow8  = (p) => <I8 {...p}><path d="M5 12h14M12 5l7 7-7 7"/></I8>;
const Info8   = (p) => <I8 {...p}><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></I8>;
const RotCam  = (p) => <I8 {...p}><path d="M20 20a8 8 0 1 0-16 0M20 20l-3-3M20 20h-4"/></I8>;

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

// ─────────────────────────────────────────────────────────────
// Mock zapisnik (vidi se u kameri i kasnije kao reference)
// ─────────────────────────────────────────────────────────────
function MockZapisnik({ scale = 1, blur = false }) {
  return (
    <div style={{
      width: '100%', aspectRatio: '1 / 1.41', // A4
      background: 'oklch(0.97 0.01 60)',
      borderRadius: 4 * scale,
      padding: 12 * scale,
      fontFamily: V8.mono, color: V8.ink800,
      boxSizing: 'border-box',
      filter: blur ? 'blur(0.5px)' : 'none',
      boxShadow: '0 4px 16px oklch(0 0 0 / 0.3)',
      transform: 'rotate(-0.4deg)',
      fontSize: 7 * scale, lineHeight: 1.4,
    }}>
      <div style={{ textAlign: 'center', fontWeight: 700, fontSize: 8 * scale, marginBottom: 6 * scale, letterSpacing: 0.5 }}>
        ZAPISNIK O RADU<br/>BIRAČKOG ODBORA
      </div>
      <div style={{ textAlign: 'center', fontSize: 6 * scale, opacity: 0.7, marginBottom: 8 * scale }}>
        Birač. mesto br. 0341/A · OŠ „V. Ribnikar"<br/>
        29.03.2026.
      </div>
      <div style={{ borderTop: '1px solid ' + V8.ink400, borderBottom: '1px solid ' + V8.ink400, padding: 4 * scale + 'px 0', marginBottom: 6 * scale, fontSize: 7 * scale }}>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Birača na listi:</span><strong>2.400</strong></div>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Glasalo birača:</span><strong>1.247</strong></div>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Izvučeno listića:</span><strong>1.247</strong></div>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Listića u kutiji:</span><strong>1.245</strong></div>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Nevažećih:</span><strong>14</strong></div>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>Važećih:</span><strong>1.231</strong></div>
      </div>
      <div style={{ fontSize: 6.5 * scale, opacity: 0.85 }}>
        REZULTATI PO LISTAMA:
        {[
          ['1. STRANKA NAPREDA', '612'],
          ['2. SOCIJ. PARTIJA', '287'],
          ['3. KOAL. OPOZICIJA', '243'],
          ['4. EKO ZELENA SR', '52'],
          ['5. NEZAVISNI', '37'],
        ].map(([n, v], i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: 1 * scale + 'px 0' }}>
            <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{n}</span>
            <strong>{v}</strong>
          </div>
        ))}
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// STEP 1 — Instructions
// ═════════════════════════════════════════════════════════════
function StepInstructions({ onStart, onBack }) {
  return (
    <div style={{ background: V8.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V8.font, color: V8.ink900 }}>
      <div style={{ paddingTop: 56 }} />
      <div style={{ display: 'flex', alignItems: 'center', padding: '8px 12px 4px' }}>
        <Tap8 onClick={onBack} style={{ width: 40, height: 40, borderRadius: 10, display: 'grid', placeItems: 'center', color: V8.ink700 }}><Back8 size={20}/></Tap8>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 14.5, fontWeight: 600, color: V8.ink900 }}>Slikanje zapisnika</div>
        <div style={{ width: 40 }} />
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '12px 20px 8px' }}>
        <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: -0.5, color: V8.ink900, marginBottom: 8 }}>Kako da slikaš zapisnik</div>
        <div style={{ fontSize: 13.5, color: V8.ink500, lineHeight: 1.55, marginBottom: 24 }}>
          Vigilo čita brojeve sa fotografije, poredi ih sa tvojim 20:00 izveštajem, i traži tvoju potvrdu pre slanja.
        </div>

        {/* When allowed */}
        <div style={{ background: V8.successBg, border: '1px solid oklch(0.88 0.07 152)', borderRadius: 12, padding: '14px 16px', marginBottom: 16, display: 'flex', alignItems: 'flex-start', gap: 10 }}>
          <Chk8 size={16} sw={2.6} style={{ color: V8.success, marginTop: 2 }}/>
          <div>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: 'oklch(0.36 0.15 152)', marginBottom: 4 }}>Slikaj tek kada BO istakne zapisnik javno</div>
            <div style={{ fontSize: 12, color: 'oklch(0.36 0.15 152)', lineHeight: 1.5 }}>
              Po Zakonu (čl. 78), zapisnik se može fotografisati tek nakon što ga BO javno istakne. Ne pokušavaj da ga slikaš pre toga — to je incident, prijavi ga.
            </div>
          </div>
        </div>

        <div style={{ fontSize: 11, fontFamily: V8.mono, color: V8.ink400, textTransform: 'uppercase', letterSpacing: 0.08, marginBottom: 12 }}>SAVETI ZA DOBRU SLIKU</div>
        <div style={{ background: 'white', border: '1px solid ' + V8.ink200, borderRadius: 14, padding: '4px 0' }}>
          {[
            { ic: <Sun8 size={16}/>, t: 'Dobro osvetljenje', s: 'Stoji blizu lampe ili prozora, ali ne tako da sija pravo u zapisnik.' },
            { ic: <Cam8 size={16}/>, t: 'Ravno, iznad zapisnika', s: 'Telefon paralelno sa zapisnikom — bez nagiba ili rotacije.' },
            { ic: <Grid8 size={16}/>, t: 'Cela tabela u okviru', s: 'Sve cifre moraju da se vide. Ako je predugačko, slikaj u 2 dela.' },
            { ic: <Warn8 size={16}/>, t: 'Bez refleksije', s: 'Ako vidiš sjajan flek na ekranu — pomeri se za par koraka.' },
          ].map((r, i, arr) => (
            <div key={i} style={{ display: 'flex', gap: 12, padding: '12px 16px', borderBottom: i === arr.length - 1 ? 'none' : '1px solid ' + V8.ink150 }}>
              <div style={{ width: 28, height: 28, borderRadius: 8, background: V8.ink100, color: V8.ink700, display: 'grid', placeItems: 'center', flexShrink: 0 }}>{r.ic}</div>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 500, color: V8.ink900 }}>{r.t}</div>
                <div style={{ fontSize: 12, color: V8.ink500, marginTop: 2, lineHeight: 1.45 }}>{r.s}</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 18, padding: '12px 14px', background: V8.infoBg, border: '1px solid oklch(0.88 0.07 245)', borderRadius: 10, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          <Info8 size={14} style={{ marginTop: 1, color: V8.info }}/>
          <div style={{ fontSize: 11.5, color: 'oklch(0.32 0.155 245)', lineHeight: 1.5 }}>
            Možeš slikati više puta. Vigilo bira najbolju verziju za OCR. Ako brojevi ne odgovaraju — upišeš ručno, sistem ne odbija.
          </div>
        </div>
      </div>

      <div style={{ padding: '14px 16px 36px' }}>
        <Tap8 onClick={onStart} style={{
          width: '100%', height: 54, background: V8.ink950, color: 'white',
          borderRadius: 14, fontFamily: V8.font, fontSize: 16, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <Cam8 size={18} sw={2}/> Otvori kameru
        </Tap8>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// STEP 2 — Camera UI
// ═════════════════════════════════════════════════════════════
function StepCamera({ onCapture, onExit }) {
  const [detected, setDetected] = React.useState(false);
  // Auto-detect after 1.5s
  React.useEffect(() => {
    const t = setTimeout(() => setDetected(true), 1500);
    return () => clearTimeout(t);
  }, []);

  return (
    <div style={{
      height: '100%', background: '#000', position: 'relative', overflow: 'hidden',
      fontFamily: V8.font, color: 'white',
    }}>
      <div style={{ paddingTop: 56 }} />

      {/* Top controls */}
      <div style={{ position: 'absolute', top: 56, left: 0, right: 0, padding: '14px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', zIndex: 5 }}>
        <Tap8 onClick={onExit} style={{ width: 40, height: 40, borderRadius: '50%', background: 'oklch(1 0 0 / 0.15)', display: 'grid', placeItems: 'center' }}><X8 size={18}/></Tap8>
        <div style={{ display: 'flex', gap: 10 }}>
          <Tap8 style={{ width: 40, height: 40, borderRadius: '50%', background: 'oklch(1 0 0 / 0.15)', display: 'grid', placeItems: 'center' }}><Bolt size={16}/></Tap8>
          <Tap8 style={{ width: 40, height: 40, borderRadius: '50%', background: 'oklch(1 0 0 / 0.15)', display: 'grid', placeItems: 'center' }}><Grid8 size={16}/></Tap8>
        </div>
      </div>

      {/* Status pill */}
      <div style={{ position: 'absolute', top: 120, left: 0, right: 0, display: 'flex', justifyContent: 'center', zIndex: 5 }}>
        <div style={{
          padding: '8px 14px',
          background: detected ? 'oklch(0.62 0.155 152 / 0.95)' : 'oklch(0 0 0 / 0.6)',
          borderRadius: 999, fontSize: 13, fontWeight: 500,
          display: 'flex', alignItems: 'center', gap: 8,
          backdropFilter: 'blur(8px)',
        }}>
          {detected
            ? <><Chk8 size={14} sw={2.4}/> Zapisnik prepoznat · drži mirno</>
            : <><Cam8 size={14} sw={2}/> Postavi zapisnik u okvir</>
          }
        </div>
      </div>

      {/* Camera viewport with frame overlay */}
      <div style={{
        position: 'absolute', top: 170, left: 0, right: 0, bottom: 180,
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '0 32px',
      }}>
        {/* Background — simulated environment (warm dim school room) */}
        <div style={{
          position: 'absolute', inset: 0,
          background:
            'radial-gradient(ellipse at 30% 40%, oklch(0.45 0.04 60), oklch(0.15 0.02 60)),' +
            'linear-gradient(180deg, oklch(0.2 0.03 60), oklch(0.1 0.02 60))',
          opacity: detected ? 0.6 : 1,
          transition: 'opacity 200ms',
        }}/>

        {/* The zapisnik in the camera frame */}
        <div style={{
          position: 'relative', width: '85%', maxWidth: 240,
          transition: 'transform 400ms cubic-bezier(0.2, 0.7, 0.3, 1)',
          transform: detected ? 'scale(1.0)' : 'scale(0.92)',
        }}>
          <MockZapisnik scale={1} blur={!detected}/>
        </div>

        {/* Corner brackets */}
        {[
          { top: 0, left: 0, br: '4px 0 0 0', rotate: 0 },
          { top: 0, right: 0, br: '0 4px 0 0', rotate: 90 },
          { bottom: 0, right: 0, br: '0 0 4px 0', rotate: 180 },
          { bottom: 0, left: 0, br: '0 0 0 4px', rotate: 270 },
        ].map((c, i) => (
          <div key={i} style={{
            position: 'absolute', ...c,
            width: 28, height: 28,
            margin: 16,
            borderLeft: '3px solid ' + (detected ? V8.success : 'white'),
            borderTop: '3px solid ' + (detected ? V8.success : 'white'),
            borderRadius: c.br,
            transform: `rotate(${c.rotate}deg)`,
            transition: 'border-color 200ms',
            opacity: 0.92,
          }}/>
        ))}
      </div>

      {/* Bottom controls */}
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '24px 0 36px', display: 'flex', alignItems: 'center', justifyContent: 'space-around', zIndex: 5 }}>
        <div style={{
          width: 48, height: 48, borderRadius: 8,
          background: 'oklch(1 0 0 / 0.15)',
          backgroundImage: 'linear-gradient(135deg, oklch(0.7 0.05 60), oklch(0.55 0.04 60))',
          border: '2px solid white',
        }}/>
        <Tap8 onClick={onCapture} style={{
          width: 76, height: 76, borderRadius: '50%',
          background: detected ? 'white' : 'oklch(1 0 0 / 0.6)',
          border: '4px solid white',
          boxShadow: '0 0 0 4px oklch(0 0 0 / 0.3), 0 8px 24px oklch(0 0 0 / 0.4)',
          transition: 'background 200ms',
        }}/>
        <Tap8 style={{ width: 48, height: 48, borderRadius: '50%', background: 'oklch(1 0 0 / 0.15)', display: 'grid', placeItems: 'center' }}><RotCam size={20}/></Tap8>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// STEP 3 — Processing
// ═════════════════════════════════════════════════════════════
function StepProcessing({ onDone, duration = 3000 }) {
  const [phase, setPhase] = React.useState(0); // 0..3
  React.useEffect(() => {
    const t1 = setTimeout(() => setPhase(1), duration * 0.25);
    const t2 = setTimeout(() => setPhase(2), duration * 0.55);
    const t3 = setTimeout(() => setPhase(3), duration * 0.85);
    const td = setTimeout(onDone, duration);
    return () => [t1, t2, t3, td].forEach(clearTimeout);
  }, [duration, onDone]);

  const steps = [
    { t: 'Učitana fotografija',     done: phase >= 1 },
    { t: 'Prepoznavanje teksta',    done: phase >= 2 },
    { t: 'Čitanje brojeva',         done: phase >= 3 },
  ];

  return (
    <div style={{ background: V8.ink950, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V8.font, color: 'white' }}>
      <div style={{ paddingTop: 80 }} />
      <div style={{ padding: '0 24px', flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{ fontSize: 11, fontFamily: V8.mono, textTransform: 'uppercase', letterSpacing: 0.1, opacity: 0.55, marginBottom: 8 }}>Vigilo OCR</div>
        <div style={{ fontSize: 24, fontWeight: 600, letterSpacing: -0.5, marginBottom: 4 }}>Čita zapisnik…</div>
        <div style={{ fontSize: 13, opacity: 0.6 }}>Neće dugo trajati.</div>

        {/* Scanned image with sweep line */}
        <div style={{
          marginTop: 28, position: 'relative',
          padding: 8, background: 'oklch(1 0 0 / 0.05)', borderRadius: 14, overflow: 'hidden',
        }}>
          <MockZapisnik scale={1.4}/>
          {/* Sweep line */}
          <div style={{
            position: 'absolute', left: 8, right: 8, height: 80,
            background: 'linear-gradient(180deg, transparent, oklch(0.6 0.2 245 / 0.4) 80%, oklch(0.7 0.2 245))',
            top: '10%',
            animation: 'm8sweep 1.6s ease-in-out infinite',
            pointerEvents: 'none',
            mixBlendMode: 'screen',
          }}/>
        </div>

        <div style={{ marginTop: 24 }}>
          {steps.map((s, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0' }}>
              <div style={{
                width: 22, height: 22, borderRadius: '50%',
                background: s.done ? V8.success : 'oklch(1 0 0 / 0.15)',
                color: s.done ? 'white' : 'oklch(1 0 0 / 0.4)',
                display: 'grid', placeItems: 'center',
                animation: !s.done && i === phase ? 'm8spin 1.2s linear infinite' : 'none',
                border: !s.done && i === phase ? '2px solid oklch(0.7 0.2 245 / 0.6)' : 'none',
                borderTopColor: !s.done && i === phase ? 'oklch(0.7 0.2 245)' : 'transparent',
              }}>{s.done && <Chk8 size={12} sw={3}/>}</div>
              <span style={{ fontSize: 13.5, color: s.done ? 'white' : 'oklch(1 0 0 / 0.55)' }}>{s.t}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// STEP 4 — Results sa poređenjem
// ═════════════════════════════════════════════════════════════
const PREV_20 = { glasalo: 1234, izvuceno: 1234, kutija: 1232 };

function StepResults({ onSubmit, onRetake, ocrFlawed = false }) {
  // OCR vrednosti — ako je flawed, jedna lista ima nesigurnu vrednost
  const fields = [
    { k: 'glasalo',  l: 'Glasalo birača',       v: 1247, prev: PREV_20.glasalo,  ok: true },
    { k: 'izvuceno', l: 'Izvučeno listića',     v: 1247, prev: PREV_20.izvuceno, ok: true },
    { k: 'kutija',   l: 'Listića u kutiji',     v: 1245, prev: PREV_20.kutija,   ok: true },
    { k: 'nevaz',    l: 'Nevažećih',            v: 14,    ok: true },
    { k: 'vaz',      l: 'Važećih',              v: 1231, ok: true },
  ];
  const liste = [
    { l: '1. Stranka napreda',     v: 612, conf: 0.99 },
    { l: '2. Socij. partija',       v: 287, conf: 0.97 },
    { l: '3. Koal. opozicija',      v: ocrFlawed ? 243 : 243, conf: ocrFlawed ? 0.71 : 0.96, unsure: ocrFlawed },
    { l: '4. Eko zelena Sr',        v: 52,  conf: 0.95 },
    { l: '5. Nezavisni',            v: 37,  conf: 0.93 },
  ];

  return (
    <div style={{ background: V8.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V8.font, color: V8.ink900 }}>
      <div style={{ paddingTop: 56 }} />
      <div style={{ display: 'flex', alignItems: 'center', padding: '8px 12px 4px' }}>
        <Tap8 onClick={onRetake} style={{ width: 40, height: 40, borderRadius: 10, display: 'grid', placeItems: 'center', color: V8.ink700 }}><Back8 size={20}/></Tap8>
        <div style={{ flex: 1, textAlign: 'center' }}>
          <div style={{ fontSize: 14.5, fontWeight: 600, color: V8.ink900 }}>Pregled zapisnika</div>
          <div style={{ fontSize: 10.5, fontFamily: V8.mono, color: V8.ink500, marginTop: 2 }}>BM 0341/A · 22:08</div>
        </div>
        <div style={{ width: 40 }} />
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 16px 16px' }}>
        {/* Photo preview thumbnail */}
        <div style={{ background: V8.ink950, borderRadius: 14, padding: 16, marginBottom: 16, display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 70, transform: 'rotate(2deg)' }}>
            <MockZapisnik scale={1}/>
          </div>
          <div style={{ flex: 1, color: 'white' }}>
            <div style={{ fontSize: 11, fontFamily: V8.mono, textTransform: 'uppercase', letterSpacing: 0.06, opacity: 0.55, marginBottom: 4 }}>OCR rezultat</div>
            <div style={{ fontSize: 15, fontWeight: 600, letterSpacing: -0.2 }}>{ocrFlawed ? '4 sigurna · 1 za proveru' : 'Svi brojevi pročitani'}</div>
            <Tap8 style={{ marginTop: 6, fontSize: 11.5, color: 'oklch(0.85 0.15 60)', fontWeight: 500, textDecoration: 'underline' }}>Slikaj ponovo</Tap8>
          </div>
        </div>

        {/* Numbers */}
        <div style={{ fontSize: 11, fontFamily: V8.mono, color: V8.ink400, textTransform: 'uppercase', letterSpacing: 0.08, marginBottom: 8 }}>Brojevi · poređenje sa 20:00</div>
        <div style={{ background: 'white', border: '1px solid ' + V8.ink200, borderRadius: 14, marginBottom: 16 }}>
          {fields.map((f, i, arr) => {
            const delta = f.prev != null ? f.v - f.prev : null;
            return (
              <div key={f.k} style={{ display: 'flex', alignItems: 'center', padding: '12px 16px', borderBottom: i === arr.length - 1 ? 'none' : '1px solid ' + V8.ink150 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, color: V8.ink800 }}>{f.l}</div>
                  {delta != null && (
                    <div style={{ fontSize: 10.5, color: V8.ink500, fontFamily: V8.mono, marginTop: 2 }}>
                      20:00 bilo {f.prev} · +{delta}
                    </div>
                  )}
                </div>
                <div style={{ fontSize: 19, fontWeight: 600, fontFamily: V8.mono, fontVariantNumeric: 'tabular-nums', color: V8.ink900, letterSpacing: -0.4 }}>{f.v.toLocaleString('fr-FR').replace(/\u202f/g, ' ').replace(/\u00a0/g, ' ')}</div>
                <Tap8 style={{ marginLeft: 12, width: 32, height: 32, borderRadius: 8, background: V8.ink75, color: V8.ink500, display: 'grid', placeItems: 'center' }}><Pencil8 size={14}/></Tap8>
              </div>
            );
          })}
        </div>

        {/* Per-list results */}
        <div style={{ fontSize: 11, fontFamily: V8.mono, color: V8.ink400, textTransform: 'uppercase', letterSpacing: 0.08, marginBottom: 8 }}>Listići po listama</div>
        <div style={{ background: 'white', border: '1px solid ' + V8.ink200, borderRadius: 14 }}>
          {liste.map((l, i, arr) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', padding: '12px 16px', borderBottom: i === arr.length - 1 ? 'none' : '1px solid ' + V8.ink150, background: l.unsure ? V8.warningBg : 'transparent' }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, color: V8.ink800 }}>{l.l}</div>
                {l.unsure && (
                  <div style={{ fontSize: 10.5, color: 'oklch(0.4 0.15 70)', fontFamily: V8.mono, marginTop: 2, display: 'flex', alignItems: 'center', gap: 4 }}>
                    <Warn8 size={11} sw={2}/> OCR nesiguran ({(l.conf * 100).toFixed(0)}%) · proveri sa zapisnika
                  </div>
                )}
              </div>
              <div style={{ fontSize: 19, fontWeight: 600, fontFamily: V8.mono, fontVariantNumeric: 'tabular-nums', color: V8.ink900, letterSpacing: -0.4 }}>{l.v}</div>
              <Tap8 style={{ marginLeft: 12, width: 32, height: 32, borderRadius: 8, background: l.unsure ? V8.warning : V8.ink75, color: l.unsure ? V8.ink950 : V8.ink500, display: 'grid', placeItems: 'center' }}><Pencil8 size={14}/></Tap8>
            </div>
          ))}
        </div>

        {/* Validation summary */}
        <div style={{ marginTop: 16, padding: '12px 14px', background: 'white', border: '1px solid ' + V8.ink200, borderRadius: 12, display: 'flex', alignItems: 'flex-start', gap: 10 }}>
          <Chk8 size={16} sw={2.6} style={{ color: V8.success, marginTop: 1 }}/>
          <div style={{ fontSize: 12, color: V8.ink700, lineHeight: 1.5 }}>
            <strong style={{ fontWeight: 600, color: V8.ink900 }}>Provera prošla:</strong> izvučeno = u kutiji + nevažeći. Suma listića po listama = važeći (1 231).
          </div>
        </div>
      </div>

      <div style={{ padding: '12px 16px 36px', borderTop: '1px solid ' + V8.ink150 }}>
        <Tap8 onClick={onSubmit} style={{
          width: '100%', height: 54, background: V8.ink950, color: 'white',
          borderRadius: 14, fontFamily: V8.font, fontSize: 16, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>Pošalji zapisnik <Arrow8 size={18} sw={2.4}/></Tap8>
        <Tap8 onClick={onRetake} style={{ marginTop: 8, width: '100%', textAlign: 'center', fontSize: 13, color: V8.ink600, padding: '8px 0' }}>
          Slikaj ponovo
        </Tap8>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// STEP 5 — Submitted
// ═════════════════════════════════════════════════════════════
function StepDoneM8({ onReset }) {
  return (
    <div style={{ background: V8.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V8.font, color: V8.ink900 }}>
      <div style={{ paddingTop: 80, padding: '80px 24px 16px', flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{
          width: 72, height: 72, borderRadius: 20, background: V8.successBg, color: V8.success,
          display: 'grid', placeItems: 'center', marginBottom: 24,
          boxShadow: '0 0 0 8px oklch(0.62 0.155 152 / 0.1)',
        }}><Chk8 size={32} sw={2.6}/></div>

        <div style={{ fontSize: 28, fontWeight: 600, letterSpacing: -0.6, color: V8.ink900, lineHeight: 1.1, marginBottom: 10 }}>
          Zapisnik je poslat
        </div>
        <div style={{ fontSize: 14.5, color: V8.ink600, lineHeight: 1.55, marginBottom: 24 }}>
          OCR podaci i fotografija sačuvani uz tvoj profil. Analitičari u HQ-u sada vide finalne brojeve za BM 0341/A.
        </div>

        <div style={{ background: 'white', border: '1px solid ' + V8.ink200, borderRadius: 14, padding: 16 }}>
          <div style={{ fontSize: 10.5, fontFamily: V8.mono, color: V8.ink400, textTransform: 'uppercase', letterSpacing: 0.06, marginBottom: 10 }}>Šta dalje</div>
          {[
            { ic: <Chk8 size={14} sw={2.6}/>, c: V8.success, t: 'Smena završena', s: '16 h · cela smena · hvala' },
            { ic: <Info8 size={14}/>,         c: V8.info,    t: 'Evaluacija stiže', s: 'CC operater će te kontaktirati za feedback u narednih 2 dana' },
          ].map((r, i, arr) => (
            <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '8px 0', borderBottom: i === arr.length - 1 ? 'none' : '1px solid ' + V8.ink150 }}>
              <div style={{ width: 22, height: 22, borderRadius: '50%', background: 'oklch(from ' + r.c + ' calc(l + 0.3) calc(c - 0.1) h / 0.3)', color: r.c, display: 'grid', placeItems: 'center', flexShrink: 0, marginTop: 2 }}>{r.ic}</div>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 500, color: V8.ink900 }}>{r.t}</div>
                <div style={{ fontSize: 11.5, color: V8.ink500, marginTop: 1, lineHeight: 1.4 }}>{r.s}</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{ flex: 1 }} />
      </div>
      <div style={{ padding: '12px 16px 36px' }}>
        <Tap8 onClick={onReset} style={{
          width: '100%', height: 54, background: V8.ink950, color: 'white',
          borderRadius: 14, fontFamily: V8.font, fontSize: 16, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>Nazad na početni</Tap8>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Flow
// ─────────────────────────────────────────────────────────────
function OCRFlow({ tweaks }) {
  const [step, setStep] = React.useState(tweaks.step || 'instructions');

  React.useEffect(() => { setStep(tweaks.step || 'instructions'); }, [tweaks.step]);

  if (step === 'instructions') return <StepInstructions onStart={() => setStep('camera')} onBack={() => setStep('instructions')}/>;
  if (step === 'camera')       return <StepCamera onCapture={() => setStep('processing')} onExit={() => setStep('instructions')}/>;
  if (step === 'processing')   return <StepProcessing onDone={() => setStep('results')} duration={tweaks.duration || 3000}/>;
  if (step === 'results')      return <StepResults onSubmit={() => setStep('done')} onRetake={() => setStep('camera')} ocrFlawed={tweaks.ocrFlawed}/>;
  return <StepDoneM8 onReset={() => setStep('instructions')}/>;
}

const m8styles = document.createElement('style');
m8styles.textContent = `
  @keyframes m8sweep { 0% { transform: translateY(0); opacity: 0.8; } 50% { transform: translateY(280%); opacity: 0.4; } 100% { transform: translateY(0); opacity: 0.8; } }
  @keyframes m8spin { 0% { transform: rotate(0); } 100% { transform: rotate(360deg); } }
`;
document.head.appendChild(m8styles);

Object.assign(window, { OCRFlow });
