// M6 — ZmAI chat (Vigilo Mobile)
// Persistent asistent za posmatrače. Odgovara na pitanja o izbornom procesu
// sa citiranim izvorima (Zakon, Priručnik). Quick-reply chip-ovi za česte teme,
// typing indikator, vidljiva istorija.

const V6 = {
  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)',
  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 I6 = ({ 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 Back6  = (p) => <I6 {...p}><path d="m15 18-6-6 6-6"/></I6>;
const Send6  = (p) => <I6 {...p}><path d="m22 2-7 20-4-9-9-4z"/><path d="M22 2 11 13"/></I6>;
const Mic6   = (p) => <I6 {...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"/></I6>;
const MicOff6= (p) => <I6 {...p}><path d="M1 1l22 22M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V4a3 3 0 0 0-5.94-.6M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23M12 19v4M8 23h8"/></I6>;
const Spk6   = (p) => <I6 {...p}><path d="M11 5 6 9H2v6h4l5 4zM19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"/></I6>;
const Phone6 = (p) => <I6 {...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"/></I6>;
const EndCall= (p) => <I6 {...p}><path d="M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-3.33-2.67m-2.67-3.34a19.79 19.79 0 0 1-3.07-8.63A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91M23 1 1 23"/></I6>;
const Book   = (p) => <I6 {...p}><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></I6>;
const Spark6 = (p) => <I6 {...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"/></I6>;
const More6  = (p) => <I6 {...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"/></I6>;

const Tap6 = ({ children, onClick, style, disabled }) => (
  <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>
);

// ─────────────────────────────────────────────────────────────
// Sample QA — biblioteka odgovora ZmAI-a
// ─────────────────────────────────────────────────────────────
const QA = {
  zapisnik: {
    q: 'Da li mogu slikati zapisnik?',
    a: 'Po **Zakonu o izboru narodnih poslanika, čl. 76**, zapisnik se može slikati **tek nakon** što ga birački odbor javno istakne na biračkom mestu — obično po zatvaranju u 20:00.\n\nAko BO pita šta radiš: pokaži akreditaciju, objasni da je pravo posmatrača da slika zapisnik nakon isticanja. Ne ulazi u raspravu — ako odbiju, prijavi kao incident.',
    src: [{ l: 'Zakon · čl. 76', s: 'Zakon o izboru' }, { l: 'Priručnik · str. 12', s: 'CRTA priručnik' }],
  },
  uticaj: {
    q: 'Šta ako neko utiče na glasača?',
    a: 'Pokušaj uticaja na glasača (gestikulacija, pokazivanje listića, agitacija) je **zakonom zabranjen**. Tvoj posao kao posmatrača: zabeleži šta vidiš, ne prilazi i ne intervenirajš sama.\n\nPrijavi kroz **Prijavi incident** sa što više detalja: ko, gde, kada, šta tačno. Sistem će klasifikovati i zvati PCC ako je potrebno.',
    src: [{ l: 'Zakon · čl. 88', s: 'Zakon o izboru' }, { l: 'Priručnik · str. 28', s: 'CRTA priručnik' }],
  },
  pauza: {
    q: 'Mogu li napustiti BM zbog pauze?',
    a: 'Da, **uz prethodno obaveštenje koordinatora**. Drugi STO na smeni mora ostati. Trudi se da pauze budu kratke (do 20 min) i ne u kritičnim trenucima (otvaranje, zatvaranje, prebrojavanje).\n\nAko si sama bez partnera — pošalji poruku koordinatoru kroz Vigilo pre nego što izađeš.',
    src: [{ l: 'Priručnik · str. 18', s: 'CRTA priručnik' }],
  },
  baterija: {
    q: 'Šta ako mi padne baterija?',
    a: 'Sistem te ne kažnjava ako kratko prekineš javljanje. Ali što duže ima signal, lakše je svima.\n\n**Pre izbornog dana**: napuni telefon do kraja, ponesi power bank. **Tokom dana**: ako padne baterija, pokušaj naći utičnicu — školi obično ima u učionicama. Javi koordinatoru kad ponovo budeš online.',
    src: [{ l: 'Priručnik · str. 6', s: 'CRTA priručnik' }],
  },
};

// ─────────────────────────────────────────────────────────────
// Rich text renderer — bolduje **xxx**
// ─────────────────────────────────────────────────────────────
function RichText({ text, color }) {
  const parts = text.split(/\n\n+/);
  return (
    <>
      {parts.map((p, pi) => (
        <p key={pi} style={{ margin: pi === 0 ? 0 : '10px 0 0', color, fontSize: 14, lineHeight: 1.55 }}>
          {p.split(/(\*\*[^*]+\*\*)/).map((seg, i) => seg.startsWith('**')
            ? <strong key={i} style={{ fontWeight: 600 }}>{seg.slice(2, -2)}</strong>
            : seg)}
        </p>
      ))}
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// Bot avatar — ZmAI mark
// ─────────────────────────────────────────────────────────────
function BotAvatar({ size = 28 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: size * 0.32,
      background: V6.ink950, color: 'white',
      display: 'grid', placeItems: 'center',
      fontFamily: V6.font, fontWeight: 700, fontSize: size * 0.42, letterSpacing: -0.5,
      position: 'relative', flexShrink: 0,
      backgroundImage: 'radial-gradient(circle at 70% 30%, oklch(0.59 0.215 25 / 0.4), transparent 65%)',
    }}>Z
      <span style={{
        position: 'absolute', bottom: 2, right: 2,
        width: size * 0.22, height: size * 0.22, borderRadius: '50%',
        background: 'oklch(0.62 0.155 152)', boxShadow: `0 0 0 ${size * 0.05}px ` + V6.paper,
      }}/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Message bubble
// ─────────────────────────────────────────────────────────────
function Bubble({ msg }) {
  const isBot = msg.from === 'bot';
  return (
    <div style={{ display: 'flex', gap: 8, marginBottom: 14, justifyContent: isBot ? 'flex-start' : 'flex-end' }}>
      {isBot && <BotAvatar size={28}/>}
      <div style={{ maxWidth: '78%', display: 'flex', flexDirection: 'column', alignItems: isBot ? 'flex-start' : 'flex-end' }}>
        <div style={{
          background: isBot ? 'white' : V6.ink950,
          color: isBot ? V6.ink900 : 'white',
          padding: '12px 14px',
          borderRadius: isBot ? '14px 14px 14px 4px' : '14px 14px 4px 14px',
          border: isBot ? '1px solid ' + V6.ink200 : 'none',
          fontSize: 14, lineHeight: 1.55,
        }}>
          {msg.typing ? (
            <div style={{ display: 'flex', gap: 4, padding: '2px 0' }}>
              {[0, 1, 2].map(i => (
                <span key={i} style={{
                  width: 6, height: 6, borderRadius: '50%',
                  background: V6.ink400,
                  animation: `m6typ 1.2s ease-in-out ${i * 0.15}s infinite`,
                }}/>
              ))}
            </div>
          ) : <RichText text={msg.text} color={isBot ? V6.ink800 : 'white'}/>}
        </div>
        {msg.src && !msg.typing && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 6, paddingLeft: 2 }}>
            {msg.src.map((s, i) => (
              <span key={i} style={{
                display: 'inline-flex', alignItems: 'center', gap: 4,
                background: V6.infoBg, color: 'oklch(0.4 0.155 245)',
                fontSize: 10.5, fontFamily: V6.mono, fontWeight: 500,
                padding: '3px 7px', borderRadius: 4,
              }}>
                <Book size={10} sw={2}/>{s.l}
              </span>
            ))}
          </div>
        )}
        <div style={{ fontSize: 10, color: V6.ink400, marginTop: 4, fontFamily: V6.mono, paddingLeft: 2, paddingRight: 2 }}>
          {msg.time}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Call screen — ZmAI voice + triage + transfer
// ─────────────────────────────────────────────────────────────
function CallScreen({ phase, onEnd }) {
  // phase: 'connecting' | 'greeting' | 'listening' | 'thinking' | 'transferring' | 'transferred'
  const [elapsed, setElapsed] = React.useState(0);
  React.useEffect(() => {
    const t = setTimeout(() => setElapsed(e => e + 1), 1000);
    return () => clearTimeout(t);
  }, [elapsed]);
  const mm = String(Math.floor(elapsed / 60)).padStart(2, '0');
  const ss = String(elapsed % 60).padStart(2, '0');

  const phaseInfo = {
    connecting:   { status: 'Pozivam ZmAI…',                 transcript: null,                                                             listening: false, color: V6.ink600 },
    greeting:     { status: 'ZmAI govori',                   transcript: { who: 'ZmAI', t: 'Zdravo Jovana. Ja sam ZmAI. Kako mogu da pomognem?' }, listening: false, color: V6.ink900 },
    listening:    { status: 'ZmAI sluša',                    transcript: { who: 'ti',   t: 'Pitao bih nešto o popunjavanju izveštaja…' },              listening: true,  color: V6.info },
    thinking:     { status: 'ZmAI razmišlja',                transcript: { who: 'ZmAI', t: 'Razumem. Ovo je nešto što bi koordinator bolje pojasnio. Prosleđujem.' }, listening: false, color: V6.ink900 },
    transferring: { status: 'Prosleđuje koordinatoru…',      transcript: { who: 'sys',  t: 'M. Stojanović — koordinator, region Beograd' }, listening: false, color: 'oklch(0.4 0.155 245)' },
    transferred:  { status: 'Prebačena · M. Stojanović',     transcript: { who: 'sys',  t: 'Razgovor preuzima koordinator. ZmAI ostaje uz tebe ako zatreba.' }, listening: false, color: 'oklch(0.4 0.155 152)' },
  }[phase] || { status: 'Veza…', transcript: null };

  // Whether the call is in "human handoff" zone — slightly different visual
  const transferred = phase === 'transferred';

  return (
    <div style={{
      height: '100%', display: 'flex', flexDirection: 'column',
      background:
        'radial-gradient(circle at 50% 0%, oklch(0.22 0.025 245), oklch(0.13 0.015 60))',
      color: 'white', fontFamily: V6.font, position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ paddingTop: 56 }} />

      {/* Status header */}
      <div style={{ padding: '12px 24px 0', textAlign: 'center' }}>
        <div style={{ fontSize: 11, fontFamily: V6.mono, textTransform: 'uppercase', letterSpacing: 0.08, opacity: 0.55, marginBottom: 6 }}>
          {transferred ? 'Vigilo · ljudski operater' : 'Vigilo · glasovni asistent'}
        </div>
        <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: -0.4 }}>{phaseInfo.status}</div>
        <div style={{ fontSize: 12, opacity: 0.55, marginTop: 6, fontFamily: V6.mono, fontVariantNumeric: 'tabular-nums' }}>{mm}:{ss}</div>
      </div>

      {/* Big avatar */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 32px' }}>
        <div style={{ position: 'relative', width: 180, height: 180, marginBottom: 32 }}>
          {/* Pulse rings — speed depends on phase */}
          {(phase === 'connecting' || phase === 'greeting' || phase === 'listening' || phase === 'thinking') && [0, 1, 2].map(i => (
            <div key={i} style={{
              position: 'absolute', inset: 0, borderRadius: '50%',
              border: '2px solid ' + (phase === 'listening' ? 'oklch(0.7 0.13 245)' : 'white'),
              opacity: 0.3,
              animation: `m6ring 2000ms cubic-bezier(0.2, 0.7, 0.3, 1) ${i * 666}ms infinite`,
            }}/>
          ))}
          {/* Center avatar */}
          <div style={{
            position: 'absolute', inset: 32, borderRadius: 30,
            background: transferred
              ? 'oklch(0.55 0.16 245)'
              : V6.ink950,
            backgroundImage: transferred
              ? 'none'
              : 'radial-gradient(circle at 65% 30%, oklch(0.59 0.215 25 / 0.5), transparent 70%)',
            display: 'grid', placeItems: 'center',
            color: 'white', fontWeight: 700, fontSize: 52, letterSpacing: -2,
            boxShadow: '0 20px 50px oklch(0 0 0 / 0.4)',
            transition: 'background 200ms',
          }}>
            {transferred ? 'MS' : 'Z'}
          </div>
        </div>

        {/* Live transcript chip */}
        {phaseInfo.transcript && (
          <div style={{
            maxWidth: 320, padding: '14px 16px',
            background: 'oklch(1 0 0 / 0.08)',
            border: '1px solid oklch(1 0 0 / 0.1)',
            borderRadius: 14,
            textAlign: 'left', width: '100%',
          }}>
            <div style={{
              fontSize: 10, fontFamily: V6.mono, textTransform: 'uppercase', letterSpacing: 0.08,
              color: phaseInfo.transcript.who === 'ti'   ? 'oklch(0.85 0.13 245)'
                   : phaseInfo.transcript.who === 'ZmAI' ? 'oklch(0.85 0.15 60)'
                   : 'oklch(0.85 0.12 152)',
              marginBottom: 5, display: 'flex', alignItems: 'center', gap: 6,
            }}>
              {phaseInfo.transcript.who === 'ti' && <Mic6 size={11} sw={2.4}/>}
              {phaseInfo.transcript.who === 'ZmAI' && <Spark6 size={11} sw={2.4}/>}
              {phaseInfo.transcript.who === 'sys' && <Phone6 size={11} sw={2.4}/>}
              {phaseInfo.transcript.who === 'ti' ? 'TI' : phaseInfo.transcript.who === 'ZmAI' ? 'ZMAI' : 'SISTEM'}
            </div>
            <div style={{ fontSize: 14, lineHeight: 1.45, color: 'oklch(0.96 0.005 60)' }}>{phaseInfo.transcript.t}</div>
          </div>
        )}
      </div>

      {/* Bottom controls */}
      <div style={{ padding: '20px 32px 40px', display: 'flex', justifyContent: 'space-around', alignItems: 'center' }}>
        <Tap6 style={{ width: 60, height: 60, borderRadius: '50%', background: 'oklch(1 0 0 / 0.1)', border: '1px solid oklch(1 0 0 / 0.15)', display: 'grid', placeItems: 'center', color: 'white' }}><MicOff6 size={22}/></Tap6>
        <Tap6 onClick={onEnd} style={{
          width: 72, height: 72, borderRadius: '50%',
          background: 'oklch(0.59 0.215 25)',
          display: 'grid', placeItems: 'center', color: 'white',
          boxShadow: '0 8px 24px oklch(0.59 0.215 25 / 0.5)',
        }}><EndCall size={28} sw={2.4}/></Tap6>
        <Tap6 style={{ width: 60, height: 60, borderRadius: '50%', background: 'oklch(1 0 0 / 0.1)', border: '1px solid oklch(1 0 0 / 0.15)', display: 'grid', placeItems: 'center', color: 'white' }}><Spk6 size={22}/></Tap6>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Chat screen
// ─────────────────────────────────────────────────────────────
function ZmAIScreen({ initialMessages, onStartCall }) {
  const [messages, setMessages] = React.useState(initialMessages);
  const [input, setInput] = React.useState('');
  const [waiting, setWaiting] = React.useState(false);
  const scrollRef = React.useRef(null);

  // Auto-scroll on new message
  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  // Reset when initial changes
  React.useEffect(() => { setMessages(initialMessages); }, [initialMessages]);

  const nowStr = () => {
    const d = new Date();
    return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
  };

  const ask = (qKey, freeText) => {
    if (waiting) return;
    const qa = qKey ? QA[qKey] : null;
    const userText = qa ? qa.q : freeText;
    if (!userText) return;
    setInput('');
    setMessages(m => [...m, { from: 'user', text: userText, time: nowStr() }]);
    setWaiting(true);
    setTimeout(() => {
      setMessages(m => [...m, { from: 'bot', typing: true, time: nowStr() }]);
    }, 250);
    setTimeout(() => {
      setMessages(m => {
        const copy = m.slice(0, -1);
        if (qa) {
          copy.push({ from: 'bot', text: qa.a, src: qa.src, time: nowStr() });
        } else {
          copy.push({
            from: 'bot',
            text: 'Tvoje pitanje sam zabeležio i prosleđujem koordinatoru. Odgovor stiže uskoro. U međuvremenu možeš pretražiti česte teme ispod.',
            time: nowStr(),
          });
        }
        return copy;
      });
      setWaiting(false);
    }, 1900);
  };

  // Suggested replies — koja nisu već pitana
  const askedKeys = new Set(messages.filter(m => m.from === 'user').map(m => {
    const found = Object.entries(QA).find(([k, v]) => v.q === m.text);
    return found ? found[0] : null;
  }).filter(Boolean));
  const suggestions = Object.entries(QA).filter(([k]) => !askedKeys.has(k));

  return (
    <div style={{ background: V6.paper, height: '100%', display: 'flex', flexDirection: 'column', fontFamily: V6.font, color: V6.ink900 }}>
      <div style={{ paddingTop: 56 }} />

      {/* Header */}
      <div style={{ padding: '8px 12px 14px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid ' + V6.ink150 }}>
        <Tap6 style={{ width: 40, height: 40, borderRadius: 10, display: 'grid', placeItems: 'center', color: V6.ink700 }}><Back6 size={20}/></Tap6>
        <BotAvatar size={36}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 600, color: V6.ink900, letterSpacing: -0.2 }}>ZmAI</div>
          <div style={{ fontSize: 11, color: V6.ink500, fontFamily: V6.mono, marginTop: 1, display: 'flex', alignItems: 'center', gap: 4 }}>
            <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'oklch(0.62 0.155 152)' }}/>
            Asistent · uvek dostupan
          </div>
        </div>
        <Tap6 onClick={onStartCall} style={{ width: 40, height: 40, borderRadius: 10, display: 'grid', placeItems: 'center', color: V6.ink950, background: V6.ink100, marginRight: 2 }}><Phone6 size={17} sw={2}/></Tap6>
        <Tap6 style={{ width: 40, height: 40, borderRadius: 10, display: 'grid', placeItems: 'center', color: V6.ink700 }}><More6 size={18}/></Tap6>
      </div>

      {/* Messages scroll */}
      <div ref={scrollRef} style={{
        flex: 1, overflowY: 'auto', padding: '16px 14px 8px',
        background:
          'radial-gradient(ellipse at 50% 0%, oklch(0.97 0.012 245 / 0.5), transparent 40%),' +
          V6.paper,
      }}>
        {/* Disclaimer */}
        <div style={{
          margin: '0 auto 14px', padding: '10px 12px',
          background: V6.infoBg, border: '1px solid oklch(0.88 0.07 245)',
          borderRadius: 10, maxWidth: 320, fontSize: 11.5, color: 'oklch(0.4 0.155 245)',
          textAlign: 'center', lineHeight: 1.45,
        }}>
          ZmAI odgovara iz <strong style={{ fontWeight: 600 }}>Zakona o izboru</strong> i <strong style={{ fontWeight: 600 }}>CRTA priručnika</strong>. Ne zamenjuje koordinatora — za hitne stvari javi se direktno.
        </div>

        {messages.map((m, i) => <Bubble key={i} msg={m}/>)}
      </div>

      {/* Quick replies + input */}
      <div style={{ padding: '8px 0 36px', background: V6.paper, borderTop: '1px solid ' + V6.ink150 }}>
        {suggestions.length > 0 && !waiting && (
          <div style={{ padding: '4px 14px 10px', overflowX: 'auto', whiteSpace: 'nowrap' }}>
            <div style={{ fontSize: 10.5, fontFamily: V6.mono, color: V6.ink400, textTransform: 'uppercase', letterSpacing: 0.06, marginBottom: 8 }}>Česta pitanja</div>
            <div style={{ display: 'flex', gap: 6 }}>
              {suggestions.map(([k, qa]) => (
                <Tap6 key={k} onClick={() => ask(k)} style={{
                  flexShrink: 0, padding: '8px 12px', background: 'white',
                  border: '1px solid ' + V6.ink200, borderRadius: 10,
                  fontSize: 12.5, fontWeight: 500, color: V6.ink800,
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>
                  <Spark6 size={13} sw={2} style={{ color: V6.red500 }}/>
                  {qa.q}
                </Tap6>
              ))}
            </div>
          </div>
        )}

        <div style={{ padding: '4px 14px 0', display: 'flex', alignItems: 'flex-end', gap: 8 }}>
          <div style={{
            flex: 1, background: 'white',
            border: '1px solid ' + V6.ink200, borderRadius: 22,
            padding: '8px 4px 8px 14px', minHeight: 40,
            display: 'flex', alignItems: 'flex-end', gap: 8,
          }}>
            <textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); ask(null, input.trim()); } }}
              placeholder="Pitaj ZmAI…"
              style={{
                flex: 1, border: 0, outline: 0, background: 'transparent',
                font: 'inherit', fontSize: 14, color: V6.ink900,
                resize: 'none', padding: '4px 0', minHeight: 20, maxHeight: 80,
                fontFamily: V6.font, lineHeight: 1.4,
              }}
              rows={1}
            />
            <Tap6 style={{
              width: 32, height: 32, borderRadius: '50%',
              display: 'grid', placeItems: 'center',
              color: V6.ink500,
            }}><Mic6 size={16}/></Tap6>
          </div>
          <Tap6 onClick={() => ask(null, input.trim())} disabled={!input.trim() || waiting} style={{
            width: 44, height: 44, borderRadius: '50%',
            background: input.trim() && !waiting ? V6.ink950 : V6.ink200,
            color: input.trim() && !waiting ? 'white' : V6.ink400,
            display: 'grid', placeItems: 'center',
          }}><Send6 size={17} sw={2.2}/></Tap6>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Flow
// ─────────────────────────────────────────────────────────────
function ZmAIFlow({ tweaks }) {
  const [mode, setMode] = React.useState(tweaks.mode || 'chat'); // chat | call
  const [callPhase, setCallPhase] = React.useState('connecting');

  // Sync from tweaks
  React.useEffect(() => {
    setMode(tweaks.mode || 'chat');
    if (tweaks.mode === 'call') {
      setCallPhase(tweaks.callPhase || 'connecting');
    }
  }, [tweaks.mode, tweaks.callPhase]);

  // Auto-progression for call (only if not pinned by tweaks)
  React.useEffect(() => {
    if (mode !== 'call' || tweaks.callPhase) return;
    const seq = [
      { phase: 'connecting',   ms: 1200 },
      { phase: 'greeting',     ms: 2800 },
      { phase: 'listening',    ms: 3000 },
      { phase: 'thinking',     ms: 2500 },
      { phase: 'transferring', ms: 2500 },
      { phase: 'transferred',  ms: 99999 },
    ];
    const i = seq.findIndex(s => s.phase === callPhase);
    if (i < 0 || i === seq.length - 1) return;
    const t = setTimeout(() => setCallPhase(seq[i + 1].phase), seq[i].ms);
    return () => clearTimeout(t);
  }, [mode, callPhase, tweaks.callPhase]);

  const initial = React.useMemo(() => {
    if (tweaks.preset === 'conversation') {
      return [
        { from: 'bot', text: 'Zdravo, Jovana. Ja sam **ZmAI**.\n\nMogu da odgovorim na pitanja o izbornom procesu — pravila, procedure, šta uraditi u različitim situacijama.', time: '14:00' },
        { from: 'user', text: QA.zapisnik.q, time: '14:02' },
        { from: 'bot', text: QA.zapisnik.a, src: QA.zapisnik.src, time: '14:02' },
        { from: 'user', text: 'A šta ako odbiju da ga istaknu?', time: '14:04' },
        { from: 'bot', text: 'To je incident. Prijavi ga kroz **„Prijavi incident"** sa što više detalja (kada si tražila, ko je odbio, da li je dat razlog).\n\nSistem će klasifikovati prijavu. Ako BO sistematski odbija isticanje — najverovatnije teški incident, PCC operater će te zvati.', src: [{ l: 'Zakon · čl. 78' }, { l: 'Priručnik · str. 14' }], time: '14:04' },
      ];
    }
    return [
      { from: 'bot', text: 'Zdravo, Jovana. Ja sam **ZmAI**.\n\nMogu da odgovorim na pitanja o izbornom procesu — pravila, procedure, šta uraditi u različitim situacijama. Pitaj me bilo šta, ili ako više voliš da pričaš naglas — pritisni dugme za poziv u gornjem desnom uglu.', time: '14:14' },
    ];
  }, [tweaks.preset]);

  if (mode === 'call') {
    return <CallScreen
      phase={callPhase}
      onEnd={() => { setMode('chat'); setCallPhase('connecting'); }}
    />;
  }
  return <ZmAIScreen initialMessages={initial} onStartCall={() => { setMode('call'); setCallPhase('connecting'); }}/>;
}

const m6styles = document.createElement('style');
m6styles.textContent = `
  @keyframes m6typ { 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; } 30% { transform: translateY(-4px); opacity: 1; } }
  @keyframes m6ring { 0% { transform: scale(0.7); opacity: 0; } 30% { opacity: 0.3; } 100% { transform: scale(1.3); opacity: 0; } }
`;
document.head.appendChild(m6styles);

Object.assign(window, { ZmAIFlow });
