// AI Construction Assistant — live-typing chat demo
const { useState: useStateA, useEffect: useEffectA, useRef: useRefA } = React;

const SCRIPT = [
  { role: 'user', text: 'Can I claim time on this delay caused by the structural engineer redesign?' },
  { role: 'bot',  text: "Yes. Under clause 18.4, a Principal-caused delay (engineer re-design qualifies) entitles you to an EOT and direct cost recovery, provided you give notice within 10 business days. Want me to draft the EOT notice?", cite: 'CL 18.4 · AS 4902-2000' },
  { role: 'user', text: 'Yes please.' },
  { role: 'bot',  text: "Drafted. The notice cites clause 18.4 and includes the 3-day re-sequencing impact on the critical path. Ready for your review.", cite: 'Notice EOT-019' },
];

function TypewriterLine({ text, onDone, speed = 14 }) {
  const [shown, setShown] = useStateA('');
  useEffectA(() => {
    let i = 0;
    let cancelled = false;
    const tick = () => {
      if (cancelled) return;
      i += 1;
      setShown(text.slice(0, i));
      if (i < text.length) setTimeout(tick, speed);
      else onDone && onDone();
    };
    setShown('');
    setTimeout(tick, 200);
    return () => { cancelled = true; };
  }, [text]);
  return <span>{shown}</span>;
}

function AssistantDemo() {
  const [shown, setShown] = useStateA([]);
  const [typing, setTyping] = useStateA(false);
  const scrollRef = useRefA(null);

  useEffectA(() => {
    let cancelled = false;
    let step = 0;

    const run = async () => {
      while (!cancelled) {
        const item = SCRIPT[step % SCRIPT.length];
        // Show typing indicator for bot only
        if (item.role === 'bot') {
          setTyping(true);
          await new Promise(r => setTimeout(r, 700));
          if (cancelled) return;
          setTyping(false);
        } else {
          await new Promise(r => setTimeout(r, 300));
          if (cancelled) return;
        }
        setShown(prev => [...prev, { ...item, key: Date.now() + Math.random() }]);
        // Wait for typewriter to finish
        const dur = Math.max(800, item.text.length * 14 + 600);
        await new Promise(r => setTimeout(r, dur));
        if (cancelled) return;
        step++;

        if (step % SCRIPT.length === 0) {
          // restart the loop
          await new Promise(r => setTimeout(r, 1800));
          if (cancelled) return;
          setShown([]);
        }
      }
    };
    run();
    return () => { cancelled = true; };
  }, []);

  useEffectA(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [shown, typing]);

  return (
    <div className="flex flex-col">
      <div className="flex items-center justify-between pb-3 border-b border-ss-grey300 mb-3">
        <div className="flex items-center gap-2 font-mono text-[11px] text-ss-grey700 uppercase tracking-wider">
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#69c765', boxShadow: '0 0 0 4px rgba(105,199,101,0.18)' }} />
          SubSync Assistant · online
        </div>
        <span className="font-mono text-[10px] text-ss-grey500">trained on AU construction practice</span>
      </div>

      <div ref={scrollRef} className="space-y-3 overflow-y-auto" style={{ minHeight: 320, maxHeight: 400 }}>
        {shown.map((m, idx) => {
          const isUser = m.role === 'user';
          const isLast = idx === shown.length - 1;
          return (
            <div key={m.key} className={`flex gap-2 ${isUser ? 'justify-end' : 'justify-start'}`}>
              {!isUser && (
                <div className="w-7 h-7 rounded-full bg-ss-blue50 flex items-center justify-center flex-shrink-0 mt-1">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="#5096FE" aria-hidden="true"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" /></svg>
                </div>
              )}
              <div
                className={`max-w-[78%] px-4 py-2.5 text-[14px] leading-relaxed ${
                  isUser
                    ? 'bg-ss-blue text-white rounded-2xl rounded-br-sm'
                    : 'bg-ss-grey100 text-ss-grey900 rounded-2xl rounded-bl-sm border border-ss-grey300'
                }`}
              >
                {isLast ? <TypewriterLine text={m.text} /> : m.text}
                {m.cite && !isUser && (
                  <div className="mt-2 pt-2 border-t border-ss-grey300 font-mono text-[10px] text-ss-blue uppercase tracking-wider">
                    {m.cite}
                  </div>
                )}
              </div>
            </div>
          );
        })}
        {typing && (
          <div className="flex gap-2 justify-start">
            <div className="w-7 h-7 rounded-full bg-ss-blue50 flex items-center justify-center flex-shrink-0 mt-1">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="#5096FE"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" /></svg>
            </div>
            <div className="bg-ss-grey100 px-4 py-3 rounded-2xl border border-ss-grey300 flex items-center gap-1">
              <span className="dot-typing" style={{ animationDelay: '0ms' }} />
              <span className="dot-typing" style={{ animationDelay: '150ms' }} />
              <span className="dot-typing" style={{ animationDelay: '300ms' }} />
            </div>
          </div>
        )}
      </div>

      <div className="mt-3 pt-3 border-t border-ss-grey300 flex items-center gap-2">
        <input
          disabled
          placeholder="Ask about a clause, deadline, claim…"
          className="flex-1 bg-ss-grey100 border border-ss-grey300 rounded-lg px-3 py-2 text-[13px] text-ss-grey700 placeholder-ss-grey500"
        />
        <button className="btn-primary !py-2 !px-3 text-[13px]">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
        </button>
      </div>

      <style>{`
        .dot-typing {
          display:inline-block; width:6px; height:6px; border-radius:50%;
          background:#5096FE;
          animation: dotBlink 1s infinite ease-in-out;
        }
        @keyframes dotBlink {
          0%, 80%, 100% { opacity: 0.25; transform: scale(0.85); }
          40% { opacity: 1; transform: scale(1.1); }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { AssistantDemo });
