// M10 — LTO unos (Vigilo Mobile)
// Dugoročni posmatrač (LTO) beleži kampanju nedeljama pre izbornog dana.
// Mirror web LTO5: shared taksonomija (window.LTO_TAX), ručna klasifikacija sa
// uslovnom logikom (funkcioner/stranka multi, meta/izvršilac), teme multi obavezno,
// "nisam siguran" override iznad fenomena, datum/vreme događaja, broj terenskih
// razgovora, izmena postojećeg unosa, A/B (AI / ručno).

const TAX = window.LTO_TAX;

const VL = {
  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)',
  red50:   'oklch(0.972 0.012 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)',
  font:    'Geist, -apple-system, system-ui, sans-serif',
  mono:    '"Geist Mono", ui-monospace, SF Mono, Menlo, monospace',
};

const IL = ({ 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 BackL  = (p) => <IL {...p}><path d="m15 18-6-6 6-6"/></IL>;
const PlusL  = (p) => <IL {...p}><path d="M5 12h14M12 5v14"/></IL>;
const TagL   = (p) => <IL {...p}><path d="M20.59 13.41 13.42 20.58a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/><circle cx="7" cy="7" r="1.5" fill="currentColor"/></IL>;
const UsersL = (p) => <IL {...p}><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></IL>;
const PinL   = (p) => <IL {...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"/></IL>;
const SparkL = (p) => <IL {...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"/></IL>;
const Cal    = (p) => <IL {...p}><rect x="3" y="4" width="18" height="18" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></IL>;
const Chk    = (p) => <IL {...p}><path d="M20 6 9 17l-5-5"/></IL>;
const Camera = (p) => <IL {...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"/></IL>;
const Mic    = (p) => <IL {...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"/></IL>;
const Link   = (p) => <IL {...p}><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></IL>;
const Arrow  = (p) => <IL {...p}><path d="M5 12h14M12 5l7 7-7 7"/></IL>;
const Search = (p) => <IL {...p}><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></IL>;
const X      = (p) => <IL {...p}><path d="M18 6 6 18M6 6l12 12"/></IL>;
const More   = (p) => <IL {...p}><circle cx="12" cy="12" r="1.5" fill="currentColor"/><circle cx="19" cy="12" r="1.5" fill="currentColor"/><circle cx="5" cy="12" r="1.5" fill="currentColor"/></IL>;
const Flag   = (p) => <IL {...p}><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/></IL>;
const Info   = (p) => <IL {...p}><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></IL>;
const Warn   = (p) => <IL {...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"/></IL>;
const EditL  = (p) => <IL {...p}><path d="M12 20h9M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z"/></IL>;
const Clock  = (p) => <IL {...p}><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></IL>;

const TapL = ({ 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>
);

// ─────────────────────────────────────────────────────────────
// Tone (boje entiteta) — usklađeno sa web lto-ds tokenima
// ─────────────────────────────────────────────────────────────
const TONE = {
  fenomen:  { color: 'oklch(0.42 0.16 70)',  bg: 'oklch(0.97 0.04 80)',   border: 'oklch(0.88 0.06 70)',  icon: <SparkL size={14}/> },
  akter:    { color: 'oklch(0.45 0.18 25)',  bg: 'oklch(0.97 0.025 25)',  border: 'oklch(0.88 0.06 25)',  icon: <UsersL size={14}/> },
  grupa:    { color: 'oklch(0.45 0.16 285)', bg: 'oklch(0.96 0.025 285)', border: 'oklch(0.88 0.05 285)', icon: <UsersL size={14}/> },
  tema:     { color: 'oklch(0.42 0.15 245)', bg: 'oklch(0.96 0.025 245)', border: 'oklch(0.88 0.06 245)', icon: <TagL size={14}/> },
  lokacija: { color: 'oklch(0.4 0.13 152)',  bg: 'oklch(0.95 0.025 152)', border: 'oklch(0.88 0.06 152)', icon: <PinL size={14}/> },
  neutral:  { color: VL.ink700,              bg: VL.ink100,               border: VL.ink200,              icon: <TagL size={14}/> },
};

const UNSURE_FIELDS = ['Fenomeni', 'Akteri', 'Politički blok', 'Ciljne grupe', 'Teme'];

// ─────────────────────────────────────────────────────────────
// Sample past reports
// ─────────────────────────────────────────────────────────────
const PAST_REPORTS = [
  {
    id: 'r3', mode: 'manual',
    title: 'Pritisak na zaposlene u JKP "Beogradske elektrane"',
    excerpt: 'Razgovori sa 3 zaposlena u JKP-u tokom protekle nedelje. Pomenuli su sastanke sa rukovodstvom gde se sugerisalo kome da glasaju...',
    date: '11. maj · 19:42',
    chips: [['akter', 'Javni funkcioner'], ['fenomen', 'Zloupotreba javnih funkcija'], ['lokacija', 'Voždovac']],
    intensity: 4, status: 'vraćen', statusNote: 'Analitičar traži pojašnjenje · 2 pitanja',
  },
  {
    id: 'r2', mode: 'manual',
    title: 'Letakovanje u večernjim časovima u zoni Vračar',
    excerpt: 'Trećeg dana zaredom vidim 4–5 osoba u istim majicama kako stavljaju letke pod brisače auta u zoni ispred BM. Slikao sam 2 letka...',
    date: '10. maj · 21:15',
    chips: [['akter', 'Aktivista'], ['fenomen', 'Negativna kampanja i govor mržnje'], ['lokacija', 'Vračar']],
    intensity: 2, status: 'objavljen',
  },
  {
    id: 'r1', mode: 'manual',
    title: 'Medijski intervju u prime time-u',
    excerpt: 'TV Pink je u 19:30 emisiji emitovala 18 min razgovora sa funkcionerom vladajuće stranke. Nije bilo pitanja iz publike...',
    date: '9. maj · 20:50',
    chips: [['akter', 'Medij'], ['fenomen', 'Zloupotreba javnih resursa'], ['lokacija', 'Beograd · celi']],
    intensity: 3, status: 'objavljen',
  },
];

// ─────────────────────────────────────────────────────────────
// Tag chip (generic, tone-based)
// ─────────────────────────────────────────────────────────────
function TagChip({ tone, label, onRemove }) {
  const t = TONE[tone] || TONE.neutral;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 8px',
      background: t.bg, color: t.color, border: '1px solid ' + t.border,
      borderRadius: 6, fontSize: 11.5, fontWeight: 500, lineHeight: 1.4,
    }}>
      <span style={{ opacity: 0.7, display: 'grid', placeItems: 'center' }}>{t.icon}</span>
      {label}
      {onRemove && (
        <TapL onClick={onRemove} style={{ marginLeft: 2, color: 'currentColor', opacity: 0.6, display: 'grid', placeItems: 'center' }}>
          <X size={11} sw={2.2}/>
        </TapL>
      )}
    </span>
  );
}

// ═════════════════════════════════════════════════════════════
// SCREEN — Past reports list
// ═════════════════════════════════════════════════════════════
function PastList({ onNew, onOpen }) {
  return (
    <div style={{ background: VL.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: VL.font, color: VL.ink900 }}>
      <div style={{ paddingTop: 56 }} />
      <div style={{ padding: '6px 20px 12px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 12 }}>
          <div>
            <div style={{ fontSize: 11, fontFamily: VL.mono, color: VL.red500, textTransform: 'uppercase', letterSpacing: 0.08, marginBottom: 4 }}>LTO posmatrač</div>
            <div style={{ fontSize: 26, fontWeight: 600, letterSpacing: -0.6, color: VL.ink900 }}>Moji LTO unosi</div>
          </div>
          <TapL style={{ padding: '6px 10px', fontSize: 12, color: VL.ink600, fontFamily: VL.mono, background: VL.ink100, borderRadius: 6 }}>
            <Search size={13}/>
          </TapL>
        </div>
        <div style={{ fontSize: 13, color: VL.ink500, lineHeight: 1.5 }}>
          21 dan do izbornog dana · 14 unosa od početka kampanje
        </div>
      </div>

      <div style={{ padding: '0 16px' }}>
        <TapL onClick={onNew} style={{
          width: '100%', display: 'flex', alignItems: 'center', gap: 12,
          padding: '14px 16px', background: VL.ink950, color: 'white',
          borderRadius: 14, textAlign: 'left',
          backgroundImage: 'radial-gradient(circle at 100% 0%, oklch(0.59 0.215 25 / 0.22), transparent 60%)',
        }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: 'oklch(1 0 0 / 0.12)', display: 'grid', placeItems: 'center' }}>
            <PlusL size={18} sw={2.2}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 600 }}>Novi LTO unos</div>
            <div style={{ fontSize: 11.5, opacity: 0.6, marginTop: 2 }}>Narativ + ručna klasifikacija</div>
          </div>
          <Arrow size={18}/>
        </TapL>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 0 36px' }}>
        <div style={{ padding: '0 20px 10px', fontSize: 11, fontFamily: VL.mono, color: VL.ink400, textTransform: 'uppercase', letterSpacing: 0.08 }}>Tvoji unosi</div>
        {PAST_REPORTS.map((r) => (
          <TapL key={r.id} onClick={() => onOpen(r.id)} style={{
            display: 'block', width: '100%', textAlign: 'left', padding: '14px 20px',
            borderTop: '1px solid ' + VL.ink150, background: 'transparent',
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: VL.ink900, lineHeight: 1.3, flex: 1, marginRight: 8 }}>{r.title}</div>
              <span style={{
                fontSize: 10, fontFamily: VL.mono, fontWeight: 600, padding: '2px 7px', borderRadius: 4,
                background: r.status === 'objavljen' ? VL.successBg : r.status === 'vraćen' ? 'oklch(0.96 0.04 25)' : VL.warningBg,
                color: r.status === 'objavljen' ? 'oklch(0.36 0.15 152)' : r.status === 'vraćen' ? 'oklch(0.42 0.18 25)' : 'oklch(0.4 0.15 70)',
                textTransform: 'uppercase', letterSpacing: 0.04, flexShrink: 0,
              }}>{r.status === 'vraćen' ? '↩ vraćen' : r.status}</span>
            </div>
            <div style={{ fontSize: 12.5, color: VL.ink500, lineHeight: 1.5, marginBottom: 10, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
              {r.excerpt}
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginBottom: 6 }}>
              {r.chips.map(([tone, label], j) => <TagChip key={j} tone={tone} label={label}/>)}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11, color: VL.ink500, fontFamily: VL.mono, marginTop: 4 }}>
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>{r.date}<span style={{ color: TONE.fenomen.color }}>· ručno (B)</span></span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                Intenzitet
                <span style={{ display: 'inline-flex', gap: 1 }}>
                  {[1, 2, 3, 4, 5].map(n => (
                    <span key={n} style={{ width: 5, height: 5, borderRadius: '50%', background: n <= r.intensity ? VL.red500 : VL.ink200 }}/>
                  ))}
                </span>
              </span>
            </div>
          </TapL>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Bottom-sheet picker (searchable, multi ili single) — kompaktan mobilni pattern
// ─────────────────────────────────────────────────────────────
function SheetPicker({ cfg, onClose }) {
  const { title, tone, options, value, onChange, single } = cfg;
  const t = TONE[tone] || TONE.neutral;
  const [q, setQ] = React.useState('');
  const filtered = options.filter(o => o.toLowerCase().includes(q.toLowerCase()));
  const toggle = (o) => {
    if (single) { onChange([o]); onClose(); return; }
    onChange(value.includes(o) ? value.filter(x => x !== o) : [...value, o]);
  };
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'oklch(0 0 0 / 0.5)', zIndex: 100, display: 'flex', alignItems: 'flex-end' }} onClick={onClose}>
      <div style={{ width: '100%', background: 'white', borderRadius: '20px 20px 0 0', padding: '20px 16px 36px', maxHeight: '74%', display: 'flex', flexDirection: 'column' }} onClick={e => e.stopPropagation()}>
        <div style={{ width: 36, height: 4, background: VL.ink200, borderRadius: 2, margin: '0 auto 16px' }}/>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <div style={{ width: 30, height: 30, borderRadius: 8, background: t.bg, color: t.color, display: 'grid', placeItems: 'center', border: '1px solid ' + t.border }}>{t.icon}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 600 }}>{title}</div>
            <div style={{ fontSize: 11.5, color: VL.ink500, fontFamily: VL.mono }}>{single ? 'izaberi jedno' : value.length + ' izabrano · možeš više'}</div>
          </div>
          <TapL onClick={onClose} style={{ width: 36, height: 36, borderRadius: 10, background: VL.ink100, color: VL.ink700, display: 'grid', placeItems: 'center' }}><X size={18}/></TapL>
        </div>

        {options.length > 6 && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: VL.ink75, border: '1px solid ' + VL.ink200, borderRadius: 10, padding: '0 12px', height: 38, marginBottom: 12 }}>
            <Search size={15} style={{ color: VL.ink400 }}/>
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={`Pretraga · ${options.length} opcija`} style={{ flex: 1, border: 0, outline: 0, background: 'transparent', font: 'inherit', fontSize: 13, color: VL.ink900 }}/>
          </div>
        )}

        <div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexWrap: 'wrap', gap: 6, padding: '4px 0' }}>
          {filtered.length === 0 && <div style={{ width: '100%', textAlign: 'center', color: VL.ink400, fontSize: 12.5, padding: 16 }}>Nema rezultata za „{q}"</div>}
          {filtered.map(o => {
            const on = value.includes(o);
            return (
              <TapL key={o} onClick={() => toggle(o)} style={{
                padding: '8px 12px', background: on ? t.color : 'white', color: on ? 'white' : VL.ink800,
                border: '1px solid ' + (on ? t.color : VL.ink200), borderRadius: 8, fontSize: 13, fontWeight: 500,
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
                {on && <Chk size={12} sw={2.6}/>}{o}
              </TapL>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// row koji otvara picker
function FieldRow({ tone, label, hint, req, values, onOpen, last }) {
  const t = TONE[tone] || TONE.neutral;
  return (
    <TapL onClick={onOpen} style={{
      display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', width: '100%', textAlign: 'left',
      borderBottom: last ? 'none' : '1px solid ' + VL.ink150,
    }}>
      <div style={{ width: 28, height: 28, borderRadius: 7, background: t.bg, color: t.color, border: '1px solid ' + t.border, display: 'grid', placeItems: 'center', flexShrink: 0 }}>{t.icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 500, color: VL.ink900 }}>{label}{req && <span style={{ color: VL.red500 }}> *</span>}</div>
        {(!values || values.length === 0) ? (
          <div style={{ fontSize: 11.5, color: VL.ink400, fontFamily: VL.mono, marginTop: 2 }}>{hint || 'nije postavljeno · tap'}</div>
        ) : (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>
            {values.map(v => <TagChip key={v} tone={tone} label={v}/>)}
          </div>
        )}
      </div>
      <PlusL size={16} style={{ color: VL.ink400 }}/>
    </TapL>
  );
}

const SECT = ({ children }) => (
  <div style={{ fontSize: 11, fontFamily: VL.mono, color: VL.ink400, textTransform: 'uppercase', letterSpacing: 0.08, marginBottom: 8 }}>{children}</div>
);
const CARD = { background: 'white', border: '1px solid ' + VL.ink200, borderRadius: 12, padding: 4, marginBottom: 16 };

// ═════════════════════════════════════════════════════════════
// SCREEN — New / Edit report
// ═════════════════════════════════════════════════════════════
function NewReport({ onBack, onSubmit, prefill, editing }) {
  const [data, setData] = React.useState(() => ({
    title: '', narrative: '',
    eventDate: '2026-05-27', eventTime: '',
    razgovori: '',
    cats: [], subs: {}, actors: [], funkcioneri: [], stranke: [], blok: '', meta: [], izvr: [], grupe: [], teme: [],
    unsure: false, unsureFields: [],
    attachments: { photo: 0, audio: 0, link: 0 },
    ...(prefill || {}),
  }));
  // ODLUKA (LTO modul): unos je isključivo RUČAN (opcija B). LTO posmatrač sam
  // odређuje fenomen, potkategoriju, aktere, blok, ciljne grupe i teme. AI opcija je ukinuta.
  const mode = 'manual';
  const [sheet, setSheet] = React.useState(null);

  const set = (patch) => setData(d => ({ ...d, ...patch }));

  // taksonomija pomoćne
  const catKey = (label) => (TAX.PHENOMENA.find(p => p.label === label) || {}).key;
  const subsForCat = (label) => (TAX.PHENOMENA.find(p => p.label === label) || {}).subs || [];
  const needFunk = data.actors.includes('Visoki državni funkcioner');
  const needStranka = data.actors.includes('Politička stranka');
  const needMeta = data.cats.some(l => TAX.META_TRIGGER_PHENOMENA.includes(catKey(l)));
  const actorLabels = [...data.actors, ...data.funkcioneri, ...data.stranke];

  const manualOk = data.cats.length > 0 && data.actors.length > 0 && data.blok && data.teme.length > 0;
  const canSubmit = data.title.trim().length >= 6 && data.narrative.trim().length >= 20
    && (data.unsure || manualOk);

  const inputStyle = { width: '100%', height: 46, padding: '0 14px', background: 'white', border: '1px solid ' + VL.ink200, borderRadius: 10, fontFamily: VL.font, fontSize: 15, color: VL.ink900, outline: 'none', boxSizing: 'border-box' };

  return (
    <div style={{ background: VL.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: VL.font, color: VL.ink900, position: 'relative' }}>
      <div style={{ paddingTop: 56 }} />
      <div style={{ display: 'flex', alignItems: 'center', padding: '8px 12px 0' }}>
        <TapL onClick={onBack} style={{ width: 40, height: 40, borderRadius: 10, display: 'grid', placeItems: 'center', color: VL.ink700 }}><BackL size={20}/></TapL>
        <div style={{ flex: 1, textAlign: 'center', fontSize: 14, fontWeight: 600, color: VL.ink900 }}>{editing ? 'Izmena LTO unosa' : 'Novi LTO unos'}</div>
        <TapL style={{ width: 40, height: 40, borderRadius: 10, display: 'grid', placeItems: 'center', color: VL.ink600, fontSize: 12, fontWeight: 500 }}>Skica</TapL>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 16px 8px' }}>
        {editing && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', background: VL.infoBg, border: '1px solid oklch(0.85 0.06 245)', borderRadius: 10, marginBottom: 14, fontSize: 12, color: 'oklch(0.32 0.155 245)' }}>
            <EditL size={14}/><span>Menjaš svoj postojeći unos <strong>#LTO-1442</strong> (dok ga analitičar ne zaključa).</span>
          </div>
        )}

        {/* Entry timestamp (kreiranje unosa) */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '8px 12px', background: VL.ink75, borderRadius: 8, marginBottom: 16, fontSize: 11, fontFamily: VL.mono, color: VL.ink600 }}>
          <Clock size={12}/>
          <span>Unos: 27.05.2026 · 19:42 · Dragan Petrović · region Beograd</span>
        </div>

        {/* Title */}
        <div style={{ marginBottom: 16 }}>
          <SECT>Naslov</SECT>
          <input value={data.title} onChange={(e) => set({ title: e.target.value })} placeholder='Kratko, npr. „Pritisak u JKP-u Voždovac"' style={inputStyle}/>
        </div>

        {/* Datum/vreme DOGAĐAJA + broj razgovora */}
        <div style={{ marginBottom: 16 }}>
          <SECT>Kada se desilo (događaj)</SECT>
          <div style={{ display: 'flex', gap: 8 }}>
            <div style={{ flex: 1.3 }}>
              <input type="date" value={data.eventDate} onChange={(e) => set({ eventDate: e.target.value })} style={{ ...inputStyle, fontFamily: VL.mono, fontSize: 13 }}/>
              <div style={{ fontSize: 10.5, color: VL.ink400, fontFamily: VL.mono, marginTop: 4 }}>datum događaja *</div>
            </div>
            <div style={{ flex: 1 }}>
              <input type="time" value={data.eventTime} onChange={(e) => set({ eventTime: e.target.value })} style={{ ...inputStyle, fontFamily: VL.mono, fontSize: 13 }}/>
              <div style={{ fontSize: 10.5, color: VL.ink400, fontFamily: VL.mono, marginTop: 4 }}>vreme · opciono</div>
            </div>
          </div>
          <div style={{ marginTop: 10 }}>
            <input type="number" min="0" inputMode="numeric" value={data.razgovori} onChange={(e) => set({ razgovori: e.target.value })} placeholder="Broj terenskih razgovora (opciono)" style={{ ...inputStyle, height: 42, fontSize: 13.5 }}/>
          </div>
        </div>

        {/* MANUAL classification */}
        {mode === 'manual' && (<React.Fragment>
          {/* Nisam siguran — IZNAD fenomena */}
          <div style={{ background: 'oklch(0.987 0.022 80)', border: '1px solid oklch(0.9 0.06 80)', borderRadius: 12, padding: 12, marginBottom: 16 }}>
            <TapL onClick={() => set({ unsure: !data.unsure })} style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%' }}>
              <div style={{ width: 26, height: 26, borderRadius: 7, background: data.unsure ? VL.warning : 'white', color: data.unsure ? 'white' : VL.warningFg, border: '1px solid ' + (data.unsure ? VL.warning : 'oklch(0.88 0.08 80)'), display: 'grid', placeItems: 'center' }}><Flag size={13}/></div>
              <div style={{ flex: 1, textAlign: 'left' }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: data.unsure ? VL.warningFg : VL.ink800 }}>{data.unsure ? 'Označeno: nisam siguran/a' : 'Nisam siguran/a kako da klasifikujem?'}</div>
                <div style={{ fontSize: 11, color: VL.ink500, fontFamily: VL.mono, marginTop: 1 }}>preskače obavezna polja · ide analitičaru</div>
              </div>
            </TapL>
            {data.unsure && (
              <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px dashed oklch(0.88 0.06 80)' }}>
                <div style={{ fontSize: 11.5, fontWeight: 600, color: VL.ink800, marginBottom: 8 }}>Za koje elemente nisi siguran/a? <span style={{ fontWeight: 400, color: VL.ink400 }}>(opciono)</span></div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {UNSURE_FIELDS.map(f => {
                    const on = data.unsureFields.includes(f);
                    return <TapL key={f} onClick={() => set({ unsureFields: on ? data.unsureFields.filter(x => x !== f) : [...data.unsureFields, f] })} style={{ padding: '6px 11px', background: on ? VL.warning : 'white', color: on ? 'white' : VL.ink700, border: '1px solid ' + (on ? VL.warning : VL.ink200), borderRadius: 8, fontSize: 12.5, fontWeight: 500, display: 'inline-flex', alignItems: 'center', gap: 5 }}>{on && <Chk size={11} sw={2.6}/>}{f}</TapL>;
                  })}
                </div>
                <div style={{ display: 'flex', gap: 7, alignItems: 'flex-start', marginTop: 10, fontSize: 11, color: VL.warningFg, lineHeight: 1.45 }}>
                  <Info size={13}/><span>Unos možeš poslati i bez obaveznih polja. Dobija „needs review" + prioritet kod analitičara.</span>
                </div>
              </div>
            )}
          </div>

          <SECT>Klasifikacija · ja biram</SECT>
          <div style={{ ...CARD, opacity: data.unsure ? 0.6 : 1 }}>
            {/* 1 Fenomeni (kategorije) */}
            <FieldRow tone="fenomen" label="Fenomeni" req={!data.unsure} values={data.cats}
              hint="kategorije · tap za izbor"
              onOpen={() => setSheet({ title: 'Fenomeni', tone: 'fenomen', options: TAX.PHENOMENA.map(p => p.label), value: data.cats, onChange: (v) => set({ cats: v }) })}/>
            {/* potkategorije po izabranoj kategoriji */}
            {data.cats.map((cl) => subsForCat(cl).length > 0 && (
              <FieldRow key={cl} tone="fenomen" label={'↳ ' + cl} values={data.subs[cl] || []} hint="potkategorije · tap"
                onOpen={() => setSheet({ title: cl + ' · potkat.', tone: 'fenomen', options: subsForCat(cl), value: data.subs[cl] || [], onChange: (v) => set({ subs: { ...data.subs, [cl]: v } }) })}/>
            ))}
            {/* 2 Tip aktera */}
            <FieldRow tone="akter" label="Tip aktera" req={!data.unsure} values={data.actors}
              onOpen={() => setSheet({ title: 'Tip aktera', tone: 'akter', options: TAX.ACTOR_TYPES.map(a => a.label), value: data.actors, onChange: (v) => set({ actors: v }) })}/>
            {/* uslovno funkcioner */}
            {needFunk && (
              <FieldRow tone="akter" label="Koji funkcioneri?" req values={data.funkcioneri} hint="uslovno · multiple"
                onOpen={() => setSheet({ title: 'Funkcioneri', tone: 'akter', options: TAX.FUNKCIONERI, value: data.funkcioneri, onChange: (v) => set({ funkcioneri: v }) })}/>
            )}
            {/* uslovno stranka */}
            {needStranka && (
              <FieldRow tone="akter" label="Koje stranke / liste?" req values={data.stranke} hint="uslovno · multiple"
                onOpen={() => setSheet({ title: 'Stranke / liste', tone: 'akter', options: TAX.STRANKE, value: data.stranke, onChange: (v) => set({ stranke: v }) })}/>
            )}
            {/* 3 Politički blok (single, inline) */}
            <div style={{ padding: '10px 12px', borderBottom: '1px solid ' + VL.ink150 }}>
              <div style={{ fontSize: 13.5, fontWeight: 500, color: VL.ink900, marginBottom: 8 }}>Politički blok{!data.unsure && <span style={{ color: VL.red500 }}> *</span>} <span style={{ fontSize: 10.5, color: VL.ink400, fontFamily: VL.mono }}>single</span></div>
              <div style={{ display: 'flex', gap: 6 }}>
                {TAX.POLITICAL_BLOCK.map(b => (
                  <TapL key={b.key} onClick={() => set({ blok: b.label })} style={{ flex: 1, height: 38, borderRadius: 9, fontSize: 12.5, fontWeight: 600, background: data.blok === b.label ? VL.ink950 : 'white', color: data.blok === b.label ? 'white' : VL.ink700, border: '1px solid ' + (data.blok === b.label ? VL.ink950 : VL.ink200) }}>{b.label}</TapL>
                ))}
              </div>
            </div>
            {/* 4 uslovno meta/izvršilac */}
            {needMeta && (<React.Fragment>
              <FieldRow tone="akter" label="Ko je meta" req values={data.meta} hint="uslovno · iz izabranih aktera"
                onOpen={() => setSheet({ title: 'Meta', tone: 'akter', options: actorLabels, value: data.meta, onChange: (v) => set({ meta: v }) })}/>
              <FieldRow tone="akter" label="Ko je izvršilac" req values={data.izvr} hint="uslovno · iz izabranih aktera"
                onOpen={() => setSheet({ title: 'Izvršilac', tone: 'akter', options: actorLabels, value: data.izvr, onChange: (v) => set({ izvr: v }) })}/>
            </React.Fragment>)}
            {/* 5 Ciljne grupe */}
            <FieldRow tone="grupa" label="Ciljne grupe" values={data.grupe} hint="opciono · multiple"
              onOpen={() => setSheet({ title: 'Ciljne grupe', tone: 'grupa', options: TAX.TARGET_GROUPS, value: data.grupe, onChange: (v) => set({ grupe: v }) })}/>
            {/* 6 Teme (multi, obavezno) */}
            <FieldRow tone="tema" label="Teme" req={!data.unsure} values={data.teme} hint="multiple · obavezno" last
              onOpen={() => setSheet({ title: 'Teme', tone: 'tema', options: TAX.THEMES, value: data.teme, onChange: (v) => set({ teme: v }) })}/>
          </div>
        </React.Fragment>)}

        {/* AI opcija ukinuta — unos je isključivo ručan (opcija B) */}

        {/* Narrative */}
        <div style={{ marginBottom: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
            <SECT>Narativ</SECT>
            <div style={{ fontSize: 11, color: VL.ink400, fontFamily: VL.mono }}>{data.narrative.length} znakova</div>
          </div>
          <textarea value={data.narrative} onChange={(e) => set({ narrative: e.target.value })}
            placeholder="Šta si video, ko, kada, gde, kakav je kontekst. Bez ocene — samo opažanja."
            style={{ width: '100%', minHeight: 160, padding: 14, background: 'white', border: '1px solid ' + VL.ink200, borderRadius: 10, fontFamily: VL.font, fontSize: 14, color: VL.ink900, lineHeight: 1.55, outline: 'none', boxSizing: 'border-box', resize: 'vertical' }}/>
        </div>

        {/* Intenzitet — NE unosi posmatrač */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px', background: VL.ink75, borderRadius: 10, marginBottom: 16, fontSize: 11.5, color: VL.ink500, fontFamily: VL.mono, lineHeight: 1.4 }}>
          <SparkL size={14}/><span>Intenzitet ne unosiš — računa ga analitičar kao analitički output.</span>
        </div>

        {/* Attachments */}
        <div style={{ marginBottom: 16 }}>
          <SECT>Prilozi · opciono</SECT>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            {[{ k: 'photo', ic: <Camera size={18}/>, l: 'Slika' }, { k: 'audio', ic: <Mic size={18}/>, l: 'Audio' }, { k: 'link', ic: <Link size={18}/>, l: 'Link' }].map(a => {
              const n = data.attachments[a.k];
              return (
                <TapL key={a.k} onClick={() => set({ attachments: { ...data.attachments, [a.k]: n >= 3 ? 0 : n + 1 } })} style={{
                  padding: '12px 8px', background: n > 0 ? VL.ink950 : 'white', color: n > 0 ? 'white' : VL.ink800,
                  border: '1px solid ' + (n > 0 ? VL.ink950 : VL.ink200), borderRadius: 10,
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, fontSize: 12, fontWeight: 500,
                }}>{a.ic}<span>{a.l}{n > 0 ? ` · ${n}` : ''}</span></TapL>
              );
            })}
          </div>
          <div style={{ fontSize: 10.5, color: VL.ink400, fontFamily: VL.mono, marginTop: 6, lineHeight: 1.4 }}>prilozi se auto-preimenuju po šifri unosa (npr. LTO-26-MLA-01442_foto-01)</div>
        </div>
      </div>

      {/* Submit */}
      <div style={{ padding: '12px 16px 36px', borderTop: '1px solid ' + VL.ink150 }}>
        {mode === 'manual' && data.unsure && (
          <div style={{ fontSize: 11, color: VL.warningFg, fontFamily: VL.mono, display: 'flex', alignItems: 'center', gap: 5, marginBottom: 8 }}><Flag size={12}/>slanje dozvoljeno bez klasifikacije · needs review</div>
        )}
        <TapL onClick={canSubmit ? onSubmit : null} disabled={!canSubmit} style={{
          width: '100%', height: 52, background: canSubmit ? VL.ink950 : VL.ink200, color: canSubmit ? 'white' : VL.ink500,
          borderRadius: 14, fontFamily: VL.font, fontSize: 15, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>{editing ? 'Sačuvaj izmene' : 'Pošalji unos'} <Arrow size={17} sw={2.4}/></TapL>
      </div>

      {sheet && <SheetPicker cfg={sheet} onClose={() => setSheet(null)}/>}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// SCREEN — Submitted
// ═════════════════════════════════════════════════════════════
function Submitted({ onReset, editing }) {
  return (
    <div style={{ background: VL.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: VL.font, color: VL.ink900 }}>
      <div style={{ paddingTop: 80, padding: '80px 24px 16px', flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{ width: 64, height: 64, borderRadius: 18, background: VL.successBg, color: VL.success, display: 'grid', placeItems: 'center', marginBottom: 20, boxShadow: '0 0 0 8px oklch(0.62 0.155 152 / 0.08)' }}>
          <Chk size={28} sw={2.6}/>
        </div>
        <div style={{ fontSize: 26, fontWeight: 600, letterSpacing: -0.5, color: VL.ink900, marginBottom: 8 }}>{editing ? 'Izmene sačuvane' : 'Unos poslat'}</div>
        <div style={{ fontSize: 14.5, color: VL.ink600, lineHeight: 1.55, marginBottom: 24 }}>
          Stiže u analitiku kampanje. Vidiš ga sa statusom <strong style={{ color: VL.ink900 }}>„u pregledu"</strong> dok analitičar ne potvrdi i ne objavi.
        </div>
        <div style={{ background: 'white', border: '1px solid ' + VL.ink200, borderRadius: 14, padding: 14 }}>
          <div style={{ fontSize: 10.5, fontFamily: VL.mono, color: VL.ink400, textTransform: 'uppercase', letterSpacing: 0.06, marginBottom: 10 }}>Šta dalje</div>
          {[
            { ic: <Chk size={12} sw={2.6}/>, t: 'Analitičar pregleda 1–2 dana', s: 'Mogu te kontaktirati za pojašnjenje' },
            { ic: <SparkL size={12}/>, t: 'Spojiće sa drugim unosima', s: 'Tvoje opažanje + drugih = obrazac' },
            { ic: <Chk size={12} sw={2.6}/>, t: 'Objavljen → vidiš u istoriji', s: 'Po potrebi ide u javni izveštaj CRTE' },
          ].map((r, i, arr) => (
            <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '8px 0', borderBottom: i === arr.length - 1 ? 'none' : '1px solid ' + VL.ink150 }}>
              <div style={{ width: 22, height: 22, borderRadius: '50%', background: VL.successBg, color: VL.success, display: 'grid', placeItems: 'center', flexShrink: 0, marginTop: 1 }}>{r.ic}</div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500, color: VL.ink900 }}>{r.t}</div>
                <div style={{ fontSize: 11.5, color: VL.ink500, marginTop: 1, lineHeight: 1.4 }}>{r.s}</div>
              </div>
            </div>
          ))}
        </div>
        <div style={{ flex: 1 }}/>
      </div>
      <div style={{ padding: '12px 16px 36px' }}>
        <TapL onClick={onReset} style={{ width: '100%', height: 52, background: VL.ink950, color: 'white', borderRadius: 14, fontFamily: VL.font, fontSize: 15, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>Nazad na listu</TapL>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Flow
// ─────────────────────────────────────────────────────────────
function LTOFlow({ tweaks }) {
  const [view, setView] = React.useState(tweaks.view || 'list');
  React.useEffect(() => { setView(tweaks.view || 'list'); }, [tweaks.view]);

  const PREFILL_SAMPLE = {
    title: 'D2D kampanja u selima Mladenovca · podela paketa',
    narrative: 'U poslednjih 7 dana posetio sela Vlaški Do i Velika Krsna (Mladenovac). U oba zabeležena svedočenja o door-to-door kampanji. Lokalni funkcioner sa 2-3 lica dolazi u kuće starijih, ostavlja paket (ulje, šećer, brašno) i „nemojte zaboraviti za koga ćete glasati". Šestoro potvrdilo, fotografije paketa nismo pribavili.',
    eventDate: '2026-05-27', eventTime: '10:00',
    razgovori: '6',
    mode: 'manual',
    cats: ['Kupovina glasova i klijentelizam'],
    subs: { 'Kupovina glasova i klijentelizam': ['Deljenje paketa'] },
    actors: ['Javni funkcioner ili službenik'],
    blok: 'Vlast',
    grupe: ['Penzioneri', 'Lokalno stanovništvo'],
    teme: ['Socijalna politika'],
    attachments: { photo: 0, audio: 1, link: 0 },
  };

  if (view === 'list')      return <PastList onNew={() => setView('new')} onOpen={() => setView('edit')}/>;
  if (view === 'submitted') return <Submitted onReset={() => setView('list')}/>;
  if (view === 'edit')      return <NewReport editing onBack={() => setView('list')} onSubmit={() => setView('submitted')} prefill={PREFILL_SAMPLE}/>;
  return <NewReport onBack={() => setView('list')} onSubmit={() => setView('submitted')} prefill={tweaks.prefill === 'sample' ? PREFILL_SAMPLE : null}/>;
}

Object.assign(window, { LTOFlow });
