const { Card: ACard, Input: AInput, Button: ABtn, Tabs: ATabs, Badge: ABadge, Select: ASelect } = window.OctanexDesignSystem_0e3b75;
const AIcon = window.OxIcon;

const SEED_CHAT = [
  { role: 'bot', text: 'привет, л. я бот-бизнес: считаю юнит-экономику, собираю брендинг и лендинги, готовлю стратегии продвижения. что делаем?' },
  { role: 'user', text: 'хочу канал про e-com, нужен нейминг и стартовая стратегия' },
  { role: 'bot', text: 'ок. 3 варианта имени: «маржа», «оборот», «чек средний». стратегия: 2 поста в день, закуп рекламы через o/market у каналов с er выше 15%, буст через o/smm на старте. собрать полный план?' },
];

function ChatMsg({ m }) {
  const isBot = m.role === 'bot';
  return (
    <div style={{ display: 'flex', justifyContent: isBot ? 'flex-start' : 'flex-end' }}>
      <div style={{
        maxWidth: '72%', padding: '10px 14px', borderRadius: 10, fontSize: 14, lineHeight: 1.55,
        background: isBot ? 'var(--surface-card)' : 'var(--accent-dim-2)',
        border: `1px solid ${isBot ? 'var(--border-hairline)' : 'var(--border-accent-dim)'}`,
      }}>
        {isBot && <div className="ox-path" style={{ fontSize: 10.5, marginBottom: 5 }}><span className="sep">o/</span>ai · бот-бизнес</div>}
        {m.text}
      </div>
    </div>
  );
}

function AiChat({ pushToast }) {
  const [msgs, setMsgs] = React.useState(SEED_CHAT);
  const [text, setText] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const endRef = React.useRef(null);
  React.useEffect(() => {
    const box = endRef.current?.parentElement;
    if (box) box.scrollTop = box.scrollHeight;
  }, [msgs, busy]);
  const send = () => {
    if (!text.trim() || busy) return;
    const t = text.trim();
    setMsgs((m) => [...m, { role: 'user', text: t }]);
    setText('');
    setBusy(true);
    setTimeout(() => {
      setMsgs((m) => [...m, { role: 'bot', text: 'принял. черновик будет в заказах через ~2 минуты — статус [ВЫПОЛНЯЕТСЯ]. пока можешь докинуть вводных: аудитория, бюджет, срок.' }]);
      setBusy(false);
    }, 1100);
  };
  return (
    <ACard style={{ display: 'flex', flexDirection: 'column', height: 480, padding: 0, overflow: 'hidden' }}>
      <div style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 12, padding: 20 }}>
        {msgs.map((m, i) => <ChatMsg key={i} m={m} />)}
        {busy && (
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-muted)' }}>
            <span style={{ color: 'var(--green-500)' }}>➜</span> бот печатает<span className="ox-caret"></span>
          </div>
        )}
        <div ref={endRef}></div>
      </div>
      <div style={{ display: 'flex', gap: 10, padding: 14, borderTop: '1px solid var(--border-hairline)', background: 'var(--surface-1)' }}>
        <AInput placeholder="спроси про бизнес, брендинг, продвижение…" value={text} onChange={setText} style={{ flex: 1 }} />
        <ABtn onClick={send} disabled={busy}><AIcon name="send" size={15} /> отправить</ABtn>
      </div>
    </ACard>
  );
}

function AiDemo({ pushToast }) {
  const [prompt, setPrompt] = React.useState('реклама маркета юзернеймов, неон, ночь');
  const [format, setFormat] = React.useState('story');
  const [stage, setStage] = React.useState('idle'); // idle | gen | done
  const [log, setLog] = React.useState([]);
  const gen = () => {
    setStage('gen'); setLog([]);
    const steps = ['запрос к отрисовщику…', 'композиция 9:16…', 'подбор палитры: green/black…', '[OK] готово за 3.8s'];
    steps.forEach((s, i) => setTimeout(() => {
      setLog((l) => [...l, s]);
      if (i === steps.length - 1) { setStage('done'); pushToast({ tone: 'green', title: 'креатив готов', description: 'демо: 1 из 3 бесплатных генераций' }); }
    }, 700 * (i + 1)));
  };
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '380px 1fr', gap: 16, alignItems: 'start' }}>
      <ACard path="demo" title="генерация рекламы">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <AInput label="промпт" value={prompt} onChange={setPrompt} hint="что рекламируем и в каком настроении" />
          <ASelect label="формат" value={format} onChange={setFormat} options={[
            { value: 'story', label: 'вертикаль 9:16 — сторис/рилс' },
            { value: 'post', label: 'квадрат 1:1 — пост' },
          ]} />
          <ABtn size="lg" loading={stage === 'gen'} onClick={gen}>
            {stage === 'gen' ? 'генерация…' : <React.Fragment><AIcon name="sparkles" size={15} /> сгенерировать</React.Fragment>}
          </ABtn>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.9, minHeight: 68 }}>
            {log.map((l, i) => (
              <div key={i}><span style={{ color: 'var(--green-500)' }}>➜</span> <span style={{ color: l.startsWith('[OK]') ? 'var(--green-400)' : undefined }}>{l}</span></div>
            ))}
            {stage === 'idle' && <span>демо: 3 генерации бесплатно, дальше от 49 ₽</span>}
          </div>
        </div>
      </ACard>
      <ACard style={{ display: 'grid', placeItems: 'center', minHeight: 480 }}>
        {stage !== 'done' ? (
          <div className="ox-grid-bg" style={{
            width: 240, height: 427, borderRadius: 12, border: '1px dashed var(--border-strong)',
            display: 'grid', placeItems: 'center', textAlign: 'center', padding: 20,
          }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.9 }}>
              превью 9:16<br/>{stage === 'gen' ? <span>рендер<span className="ox-caret"></span></span> : 'появится здесь'}
            </span>
          </div>
        ) : (
          <div style={{
            width: 240, height: 427, borderRadius: 12, overflow: 'hidden', position: 'relative',
            background: 'var(--black-1)', border: '1px solid var(--border-accent-dim)', boxShadow: 'var(--glow-accent)',
            display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', padding: 18,
          }} className="ox-grid-bg">
            <span className="ox-glow-spot" style={{ top: -140, right: -120, width: 300, height: 300 }}></span>
            <ABadge tone="green" dot style={{ position: 'absolute', top: 14, left: 14 }}>демо</ABadge>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 700, lineHeight: 1.15, marginBottom: 8, position: 'relative' }}>
              твой юзернейм уже на аукционе
            </div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-secondary)', marginBottom: 14, position: 'relative' }}>ставки от 12 TON · комиссия 4%</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, position: 'relative' }}>o<span style={{ color: 'var(--green-500)' }}>/</span>ctanex</div>
          </div>
        )}
      </ACard>
    </div>
  );
}

function Ai({ pushToast }) {
  const [tab, setTab] = React.useState('chat');
  return (
    <div>
      <ScreenTitle greeting="// ии-враппер: чат + генерация" title="ии-студия"
        right={<ABadge tone="green" dot>sonnet online</ABadge>} />
      <div style={{ display: 'flex', marginBottom: 20 }}>
        <ATabs variant="contained" active={tab} onChange={setTab} items={[
          { id: 'chat', label: 'чат с ботом' },
          { id: 'demo', label: 'демо-реклама' },
        ]} />
      </div>
      {tab === 'chat' ? <AiChat pushToast={pushToast} /> : <AiDemo pushToast={pushToast} />}
    </div>
  );
}

Object.assign(window, { Ai });
