/* Chat-style mock of Gally conversation - used in hero */
// Use React.useState/useEffect/useRef directly to avoid scope collisions

function GallyAvatar({ size = 28, dark = false }) {
  // Simple geometric avatar - square + circle + diamond stacked
  const cls = dark ? 'gally-avatar-dark' : 'gally-avatar';
  return (
    <div className={`${cls} rounded-md flex items-center justify-center ring-1 ring-black/10`}
         style={{ width: size, height: size }}>
      <svg viewBox="0 0 24 24" width={size*0.62} height={size*0.62} aria-hidden="true">
        <circle cx="12" cy="12" r="4.2" fill="none" stroke={dark ? '#E6E6DE' : '#0B1220'} strokeWidth="1.4"/>
        <rect x="7.5" y="7.5" width="9" height="9" rx="1" fill="none" stroke={dark ? '#E6E6DE' : '#0B1220'} strokeWidth="1.4" transform="rotate(45 12 12)"/>
        <circle cx="12" cy="12" r="1.2" fill={dark ? '#E6E6DE' : '#0B1220'}/>
      </svg>
    </div>
  );
}

function UserAvatar({ size = 28 }) {
  return (
    <div className="rounded-md bg-ink-900 text-paper-0 flex items-center justify-center ring-1 ring-black/10 mono font-bold"
         style={{ width: size, height: size, fontSize: size*0.42 }}>
      N
    </div>
  );
}

/* Messages shown in the hero chat */
const HERO_SCRIPT = [
  { who: 'me', text: 'ガリィ、昨日のスクリプト、本番で落ちた。', t: '23:14' },
  { who: 'ai', text: '原因は環境変数の読み込み順。.envの先頭にBOMが混入してる可能性が高い。ログを見せて。', t: '23:14' },
  { who: 'me', text: '（ログ貼り付け）...これ詰んでる？', t: '23:16' },
  { who: 'ai', text: '詰んでない。3行で直る。ただし、同じ失敗を繰り返さないために"なぜ起きたか"を先に整理しよう。', t: '23:16' },
  { who: 'me', text: 'それ、LINEの読者にも共有したい。', t: '23:18' },
  { who: 'ai', text: 'いいね。実験ログ#037として下書きを作る。', t: '23:18', tag: 'log-037' },
];

function Bubble({ who, text, t, tag, delay = 0 }) {
  const mine = who === 'me';
  return (
    <div className={`msg-in flex gap-2 ${mine ? 'justify-end' : 'justify-start'}`}
         style={{ animationDelay: `${delay}ms` }}>
      {!mine && <GallyAvatar size={28}/>}
      <div className={`max-w-[78%] ${mine ? 'items-end' : 'items-start'} flex flex-col`}>
        <div className={[
          'px-3 py-2 rounded-2xl text-[13.5px] leading-relaxed',
          mine
            ? 'bg-ink-900 text-paper-0 rounded-br-md'
            : 'bg-paper-0 text-ink-900 rounded-bl-md ring-1 ring-ink-900/10'
        ].join(' ')}>
          {text}
          {tag && (
            <span className="ml-2 mono text-[10.5px] px-1.5 py-0.5 rounded bg-line/15 text-line2 ring-1 ring-line/30 align-middle">
              #{tag}
            </span>
          )}
        </div>
        <div className={`mono text-[10px] text-ink-400 mt-0.5 ${mine ? 'pr-1' : 'pl-1'}`}>{t}</div>
      </div>
      {mine && <UserAvatar size={28}/>}
    </div>
  );
}

function TypingBubble() {
  return (
    <div className="msg-in flex gap-2 justify-start">
      <GallyAvatar size={28}/>
      <div className="bg-paper-0 ring-1 ring-ink-900/10 rounded-2xl rounded-bl-md px-3 py-2 flex items-center gap-1">
        <span className="dot w-1.5 h-1.5 bg-ink-400 rounded-full inline-block"></span>
        <span className="dot w-1.5 h-1.5 bg-ink-400 rounded-full inline-block"></span>
        <span className="dot w-1.5 h-1.5 bg-ink-400 rounded-full inline-block"></span>
      </div>
    </div>
  );
}

function HeroChat() {
  const [visibleCount, setVisibleCount] = React.useState(0);
  const [typing, setTyping] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    let cancelled = false;
    let timeouts = [];
    const run = () => {
      setVisibleCount(0);
      setTyping(false);
      let delay = 400;
      HERO_SCRIPT.forEach((m, i) => {
        if (m.who === 'ai') {
          timeouts.push(setTimeout(() => { if (!cancelled) setTyping(true); }, delay));
          delay += 650;
          timeouts.push(setTimeout(() => {
            if (!cancelled) { setTyping(false); setVisibleCount(i+1); }
          }, delay));
        } else {
          timeouts.push(setTimeout(() => {
            if (!cancelled) setVisibleCount(i+1);
          }, delay));
        }
        delay += 900;
      });
      // Loop
      timeouts.push(setTimeout(() => {
        if (!cancelled) run();
      }, delay + 4200));
    };
    run();
    return () => { cancelled = true; timeouts.forEach(clearTimeout); };
  }, []);

  React.useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [visibleCount, typing]);

  return (
    <div className="relative">
      {/* device-ish frame */}
      <div className="absolute -inset-3 rounded-[28px] bg-ink-900/5 ring-1 ring-ink-900/5 hidden sm:block"></div>
      <div className="relative rounded-[22px] bg-paper-100 ring-1 ring-ink-900/10 overflow-hidden shadow-[0_24px_60px_-20px_rgba(11,18,32,0.35)]">
        {/* Chat header */}
        <div className="flex items-center gap-2.5 px-4 py-3 bg-paper-0 border-b border-ink-900/8">
          <GallyAvatar size={32}/>
          <div className="flex-1 min-w-0">
            <div className="text-[13px] font-bold tracking-tight flex items-center gap-1.5">
              ガリィ
              <span className="mono text-[10px] text-ink-400 font-normal">/ AI assistant</span>
            </div>
            <div className="flex items-center gap-1.5 text-[10.5px] text-ink-500 mono">
              <span className="w-1.5 h-1.5 rounded-full bg-line inline-block"></span>
              online · thinking
            </div>
          </div>
          <div className="mono text-[10px] text-ink-400 text-right leading-tight">
            session #1284<br/>23:14 JST
          </div>
        </div>

        {/* Chat body */}
        <div ref={scrollRef} className="grid-paper px-3 sm:px-4 py-4 space-y-2.5 h-[360px] sm:h-[380px] overflow-hidden">
          {HERO_SCRIPT.slice(0, visibleCount).map((m, i) => (
            <Bubble key={i} {...m} delay={i === visibleCount - 1 ? 0 : 0}/>
          ))}
          {typing && <TypingBubble/>}
        </div>

        {/* Input (decorative) */}
        <div className="flex items-center gap-2 px-3 py-2.5 bg-paper-0 border-t border-ink-900/8">
          <Icon.Paperclip size={16} className="text-ink-400"/>
          <div className="flex-1 rounded-full bg-paper-100 ring-1 ring-ink-900/8 px-3 py-1.5 text-[12px] text-ink-400">
            メッセージを入力<span className="caret"></span>
          </div>
          <div className="w-7 h-7 rounded-full bg-ink-900 text-paper-0 grid place-items-center">
            <Icon.ArrowRight size={14}/>
          </div>
        </div>
      </div>

      {/* annotations around the chat */}
      <div className="hidden lg:block absolute -left-24 top-12 text-right">
        <div className="mono text-[10px] text-ink-400 leading-tight">log-037<br/>deploy crash</div>
        <svg width="80" height="40" className="ml-auto text-ink-400" viewBox="0 0 80 40" fill="none" aria-hidden>
          <path d="M2 8 Q40 30 78 22" stroke="currentColor" strokeWidth="1" strokeDasharray="2 3"/>
          <path d="m72 18 8 4-6 6" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
        </svg>
      </div>
      <div className="hidden lg:block absolute -right-24 bottom-20 text-left">
        <svg width="80" height="40" className="text-ink-400" viewBox="0 0 80 40" fill="none" aria-hidden>
          <path d="M78 8 Q40 30 2 22" stroke="currentColor" strokeWidth="1" strokeDasharray="2 3"/>
          <path d="m8 18-6 4 6 6" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
        </svg>
        <div className="mono text-[10px] text-ink-400 leading-tight">↑ここで突破口<br/>→ 次号で公開</div>
      </div>
    </div>
  );
}

Object.assign(window, { HeroChat, GallyAvatar, UserAvatar, Bubble });
