/* ============================================================
   screen_chat.jsx — AI onboarding advisor (the wow)
   Conversational, builds the profile live in a tray, then
   hands off to the assembled profile / home.
   ============================================================ */

/* ---------- profile tray fact chip ---------- */
function TrayChip({ fk, lang, t, index }) {
  const fact = TRAY[fk];
  if (!fact) return null;
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 8, padding: '7px 12px 7px 9px',
      borderRadius: 'var(--r-full)', background: 'var(--surface)', border: '1px solid var(--border)',
      boxShadow: 'var(--shadow-1)', whiteSpace: 'nowrap', flexShrink: 0,
      animation: `chipFly .5s var(--spring) ${index * 0.05}s both`,
    }}>
      <span style={{
        width: 26, height: 26, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: 'var(--brand-tint)', color: 'var(--amber-deep)', flexShrink: 0,
      }}><Icon name={fact.icon} size={15} stroke={2.2} /></span>
      <span style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.15 }}>
        <span style={{ fontSize: 9.5, fontWeight: 700, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '.4px' }}>{t[fact.key]}</span>
        <span style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--text)' }}>{tr(fact.val, lang)}</span>
      </span>
    </div>
  );
}

function ProfileTray({ revealed, lang, t }) {
  const pct = Math.min(86, Math.round((revealed.length / 6) * 86));
  if (revealed.length === 0) return null;
  return (
    <div style={{
      flexShrink: 0, padding: '10px 14px', borderBottom: '1px solid var(--border)',
      background: 'color-mix(in srgb, var(--surface) 70%, transparent)',
      backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
      animation: 'fadeUp .4s var(--ease-out) both',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <Ring value={pct} size={46} stroke={5} run={true} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '.4px' }}>{t.trayTitle}</div>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text)' }}>{t.profileAssembling}…</div>
        </div>
      </div>
      <div className="noscroll" style={{ display: 'flex', gap: 8, overflowX: 'auto', marginTop: 10, paddingBottom: 2 }}>
        {revealed.map((fk, i) => <TrayChip key={fk} fk={fk} lang={lang} t={t} index={i} />)}
      </div>
    </div>
  );
}

/* ---------- typing dots ---------- */
function Typing() {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, animation: 'fadeUp .3s ease both' }}>
      <AdvisorDot />
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: '4px 18px 18px 18px', padding: '14px 16px', display: 'flex', gap: 5, boxShadow: 'var(--shadow-1)' }}>
        {[0, 1, 2].map(i => (
          <span key={i} style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--text-3)', animation: `typing 1.1s infinite ${i * 0.15}s` }} />
        ))}
      </div>
    </div>
  );
}
function AdvisorDot() {
  return (
    <div style={{
      width: 30, height: 30, borderRadius: '50%', flexShrink: 0,
      background: 'linear-gradient(150deg,var(--amber-soft),var(--amber))',
      display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--indigo-900)',
      boxShadow: '0 4px 12px var(--amber-glow)',
    }}><Icon name="spark" size={17} stroke={2.4} /></div>
  );
}

/* ---------- bubbles ---------- */
function AiBubble({ children }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, animation: 'fadeUp .4s var(--ease-out) both' }}>
      <AdvisorDot />
      <div style={{
        maxWidth: '80%', background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: '4px 18px 18px 18px', padding: '12px 15px', fontSize: 14.5, lineHeight: 1.45,
        color: 'var(--text)', boxShadow: 'var(--shadow-1)',
      }}>{children}</div>
    </div>
  );
}
function UserBubble({ children, file }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'flex-end', animation: 'slideInRight .35s var(--ease-out) both' }}>
      <div style={{
        maxWidth: '80%', borderRadius: '18px 4px 18px 18px', padding: file ? '10px 12px' : '12px 15px',
        background: 'linear-gradient(150deg,var(--indigo-500),var(--indigo-700))', color: '#fff',
        fontSize: 14.5, lineHeight: 1.4, fontWeight: 500, boxShadow: '0 6px 16px rgba(20,29,58,.25)',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        {file && <span style={{ width: 34, height: 34, borderRadius: 9, background: 'rgba(255,255,255,.16)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="cap" size={18} stroke={2} /></span>}
        {children}
      </div>
    </div>
  );
}

/* ---------- upload card ---------- */
function UploadCard({ onUpload, t }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, animation: 'popIn .4s var(--spring) both' }}>
      <AdvisorDot />
      <button onClick={onUpload} style={{
        textAlign: 'left', maxWidth: '82%', width: '100%',
        background: 'linear-gradient(150deg,var(--brand-tint),var(--surface))',
        border: '1.5px dashed var(--border-2)', borderRadius: '4px 18px 18px 18px',
        padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12, boxShadow: 'var(--shadow-1)',
      }}>
        <span style={{ width: 42, height: 42, borderRadius: 12, flexShrink: 0, background: 'var(--brand-soft)', color: 'var(--brand)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="clip" size={20} stroke={2} />
        </span>
        <span style={{ flex: 1 }}>
          <span style={{ display: 'block', fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>{t.attach}</span>
          <span style={{ display: 'block', fontSize: 12, color: 'var(--text-3)', marginTop: 2 }}>PDF · JPG · {t.voiceHint}</span>
        </span>
        <Icon name="arrow" size={18} stroke={2} style={{ color: 'var(--amber-deep)' }} />
      </button>
    </div>
  );
}

/* ---------- parsing overlay (inline) ---------- */
function ParsingCard({ t }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, animation: 'fadeUp .3s ease both' }}>
      <AdvisorDot />
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: '4px 18px 18px 18px', padding: '14px 16px', width: '78%', boxShadow: 'var(--shadow-1)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
          <span style={{ width: 26, height: 26, borderRadius: '50%', border: '2.5px solid var(--surface-3)', borderTopColor: 'var(--amber)', animation: 'ringRotate .8s linear infinite' }} />
          <span style={{ fontSize: 13.5, fontWeight: 700 }}>{t.parsing}…</span>
        </div>
        {[88, 64, 76].map((w, i) => (
          <div key={i} className="shimmer" style={{ height: 9, borderRadius: 6, width: w + '%', marginTop: 7 }} />
        ))}
      </div>
    </div>
  );
}

/* ---------- assemble overlay ---------- */
function AssembleOverlay({ t }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 30, display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center', gap: 22,
      background: 'color-mix(in srgb, var(--bg) 78%, transparent)', backdropFilter: 'blur(8px)',
      animation: 'fadeIn .3s ease both',
    }}>
      <div style={{ position: 'relative', width: 120, height: 120, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {[0, 1, 2].map(i => (
          <span key={i} style={{ position: 'absolute', inset: 0, borderRadius: '50%', border: '2px solid var(--amber)', animation: `pulseRing 2s ${i * 0.5}s infinite ease-out` }} />
        ))}
        <div style={{ width: 76, height: 76, borderRadius: '50%', background: 'linear-gradient(150deg,var(--amber-soft),var(--amber))', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--indigo-900)', boxShadow: '0 10px 30px var(--amber-glow)', animation: 'floaty 2.4s ease-in-out infinite' }}>
          <Icon name="spark" size={34} stroke={2.2} />
        </div>
      </div>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontSize: 18, fontWeight: 800 }}>{t.profileAssembling}…</div>
        <div style={{ fontSize: 13.5, color: 'var(--text-2)', marginTop: 4 }}>{t.value} · {t.skills} · {t.role}</div>
      </div>
    </div>
  );
}

/* ---------- main chat screen ---------- */
function ChatScreen({ lang, theme, setLang, setTheme, onFinish, onSkip, t }) {
  const [items, setItems] = useState([]);
  const [revealed, setRevealed] = useState([]);
  const [typing, setTyping] = useState(false);
  const [awaiting, setAwaiting] = useState(null);
  const [special, setSpecial] = useState(null); // 'upload' | 'parsing' | 'assemble'
  const [finished, setFinished] = useState(false);
  const idx = useRef(0);
  const scroller = useRef(null);
  const started = useRef(false);

  const push = (it) => setItems(p => [...p, { id: Math.random(), ...it }]);
  const reveal = (keys) => {
    keys.forEach((k, i) => setTimeout(() => setRevealed(p => p.includes(k) ? p : [...p, k]), i * 280));
  };

  const run = () => {
    const step = CHAT[idx.current];
    if (!step) { setFinished(true); return; }
    if (step.who === 'ai') {
      setTyping(true);
      const len = tr(step.text, 'ru').length;
      setTimeout(() => {
        setTyping(false);
        push({ who: 'ai', textObj: step.text });
        if (step.add) reveal(step.add);
        idx.current++;
        setTimeout(run, 420);
      }, Math.min(1500, 700 + len * 7));
    } else if (step.who === 'choices') {
      setAwaiting(step);
    } else if (step.who === 'upload') {
      setSpecial('upload');
    } else if (step.who === 'assemble') {
      setSpecial('assemble');
      setTimeout(() => { setSpecial(null); idx.current++; run(); }, 2400);
    }
  };

  useEffect(() => {
    if (started.current) return;
    started.current = true;
    setTimeout(run, 500);
  }, []);

  useEffect(() => {
    const el = scroller.current;
    if (el) el.scrollTop = el.scrollHeight + 200;
  }, [items, typing, special, awaiting, finished]);

  const pick = (opt) => {
    const step = awaiting;
    setAwaiting(null);
    push({ who: 'user', textObj: opt });
    if (step.add) reveal(step.add);
    idx.current++;
    setTimeout(run, 350);
  };

  const doUpload = () => {
    setSpecial('parsing');
    setTimeout(() => {
      push({ who: 'user', file: true, textObj: { ru: 'Диплом_маркетинг.pdf', uz: 'Diplom_marketing.pdf' } });
      setSpecial(null);
      idx.current++;
      setTimeout(run, 450);
    }, 2300);
  };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0, position: 'relative' }}>
      {special === 'assemble' && <AssembleOverlay t={t} />}

      {/* advisor header */}
      <div style={{ flexShrink: 0, padding: '4px 16px 12px', display: 'flex', alignItems: 'center', gap: 11 }}>
        <AdvisorDot />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 16, fontWeight: 800, letterSpacing: '-.3px' }}>{t.advisor}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--good)', fontWeight: 600 }}>
            <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--good)' }} />
            {typing ? t.typing + '…' : t.online}
          </div>
        </div>
        {onSkip && (
          <button onClick={onSkip} style={{ height: 36, padding: '0 12px', borderRadius: 'var(--r-full)', background: 'transparent', color: 'var(--text-3)', border: '1px solid var(--border)', fontWeight: 700, fontSize: 12 }}>{t.skip.split(' ')[0]}</button>
        )}
        <QuickToggles lang={lang} setLang={setLang} theme={theme} setTheme={setTheme} />
      </div>

      <ProfileTray revealed={revealed} lang={lang} t={t} />

      {/* messages */}
      <div ref={scroller} className="noscroll" style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '16px 16px 8px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {items.map(it => (
          it.who === 'ai'
            ? <AiBubble key={it.id}>{tr(it.textObj, lang)}</AiBubble>
            : <UserBubble key={it.id} file={it.file}>{tr(it.textObj, lang)}</UserBubble>
        ))}
        {special === 'upload' && <UploadCard onUpload={doUpload} t={t} />}
        {special === 'parsing' && <ParsingCard t={t} />}
        {typing && <Typing />}
        {finished && (
          <div style={{ animation: 'popIn .5s var(--spring) both', marginTop: 4 }}>
            <button onClick={onFinish} style={{
              width: '100%', height: 56, borderRadius: 'var(--r-lg)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              background: 'linear-gradient(150deg,var(--amber-soft),var(--amber))', color: 'var(--indigo-900)',
              fontSize: 16, fontWeight: 800, boxShadow: '0 12px 28px var(--amber-glow)',
            }}>
              {t.showProfile}
              <Icon name="arrow" size={20} stroke={2.4} />
            </button>
          </div>
        )}
        <div style={{ height: 4 }} />
      </div>

      {/* quick replies + input */}
      <div style={{ flexShrink: 0, padding: '0 14px', background: 'transparent' }}>
        {awaiting && (
          <div className="noscroll" style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '4px 2px 10px', flexWrap: 'wrap' }}>
            {awaiting.options.map((o, i) => (
              <button key={i} onClick={() => pick(o)} style={{
                padding: '10px 16px', borderRadius: 'var(--r-full)', fontSize: 13.5, fontWeight: 700,
                background: o.pick ? 'var(--brand)' : 'var(--surface)', color: o.pick ? '#fff' : 'var(--text-2)',
                border: o.pick ? '1px solid transparent' : '1px solid var(--border)', boxShadow: 'var(--shadow-1)',
                animation: `chipFly .4s var(--spring) ${i * 0.06}s both`,
              }}>{tr(o, lang)}</button>
            ))}
          </div>
        )}
      </div>
      <div style={{ flexShrink: 0, padding: '6px 14px 10px', display: 'flex', alignItems: 'center', gap: 9 }}>
        <div style={{ flex: 1, height: 46, borderRadius: 'var(--r-full)', background: 'var(--surface)', border: '1px solid var(--border)', display: 'flex', alignItems: 'center', padding: '0 16px', color: 'var(--text-3)', fontSize: 14, boxShadow: 'var(--shadow-1)' }}>
          {t.inputPh}
        </div>
        <button onClick={() => special === 'upload' && doUpload()} style={{ width: 46, height: 46, borderRadius: '50%', background: 'var(--surface)', border: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-2)', boxShadow: 'var(--shadow-1)' }}>
          <Icon name="clip" size={20} stroke={2} />
        </button>
        <button style={{ width: 46, height: 46, borderRadius: '50%', background: 'linear-gradient(150deg,var(--indigo-500),var(--indigo-700))', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', boxShadow: '0 6px 16px rgba(20,29,58,.3)', position: 'relative' }}>
          <span style={{ position: 'absolute', inset: 0, borderRadius: '50%', border: '2px solid var(--indigo-400)', animation: 'pulseRing 2.4s infinite ease-out', opacity: .5 }} />
          <Icon name="mic" size={20} stroke={2} />
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { ChatScreen });
