// Modül Detay + Ders Görünümü + Quiz + Canlı Prompt Denemesi
// Module page + Lesson view + Quiz + Live prompt try
function ModulePage({ moduleId, activeLesson, setActiveLesson, setPage, setModule, onComplete }) {
  const data = window.APP_DATA;
  const mod = data.modules[moduleId];
  const lessonSet = data.lessonContent[moduleId] || data.lessonContent[0];
  const t = window.t;

  const colorMap = {
    moss: '#4F9D52', sun: '#F2A63B', coral: '#E86A4F',
    lavender: '#8A7AD1', sky: '#5CA5C7', rose: '#D6739A',
  };
  const mainColor = colorMap[mod.color];

  if (activeLesson !== null) {
    const lesson = lessonSet.lessons[activeLesson];
    return (
      <LessonView
        mod={mod}
        lesson={lesson}
        lessonIndex={activeLesson}
        totalLessons={lessonSet.lessons.length}
        onBack={() => setActiveLesson(null)}
        onNext={() => {
          if (activeLesson < lessonSet.lessons.length - 1) setActiveLesson(activeLesson + 1);
          else setActiveLesson(null);
        }}
        onComplete={onComplete}
      />
    );
  }

  return (
    <div className="page fade-up">
      {/* Back nav */}
      <button onClick={() => setPage('path')} className="row" style={{
        gap: 6, color: 'var(--ink-2)', fontSize: 13, fontWeight: 500,
        padding: '6px 12px 6px 4px', borderRadius: 8, marginBottom: 20,
      }}>
        <Icon name="arrow" size={14} /> <span style={{ transform: 'rotate(180deg)', display: 'inline-block' }}></span>{t('module.back')}
      </button>

      {/* Header banner */}
      <div style={{
        background: `linear-gradient(135deg, var(--${mod.color}-soft) 0%, ${mainColor}40 100%)`,
        borderRadius: 'var(--r-xl)',
        padding: '36px 40px',
        display: 'grid',
        gridTemplateColumns: '1fr 220px',
        gap: 32,
        alignItems: 'center',
        marginBottom: 28,
        position: 'relative',
        overflow: 'hidden',
      }}>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <div className="row" style={{ gap: 8, marginBottom: 14 }}>
            <span className="chip" style={{ background: 'rgba(255,255,255,0.75)', color: 'var(--ink-2)' }}>
              {t('common.module')} {String(mod.id + 1).padStart(2, '0')}
            </span>
            <span className={`chip chip-${mod.color}`}>{mod.level}</span>
            <span className="chip" style={{ background: 'rgba(255,255,255,0.75)' }}>
              <Icon name="clock" size={12} /> {mod.duration}
            </span>
          </div>
          <h1 className="page-title" style={{ fontSize: 44, marginBottom: 12 }}>{mod.title}</h1>
          <p style={{ fontSize: 17, color: 'var(--ink-2)', maxWidth: 520, lineHeight: 1.45 }}>{mod.desc}</p>
        </div>
        <div style={{
          display: 'grid', placeItems: 'center',
          background: `radial-gradient(circle, rgba(255,255,255,0.5), transparent 70%)`,
        }}>
          <span style={{
            fontSize: 140, transform: 'rotate(-6deg)',
            filter: 'drop-shadow(0 10px 12px rgba(0,0,0,0.15))',
          }}>{mod.emoji}</span>
        </div>
      </div>

      {/* Two-column: lessons + sidebar */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 32 }}>
        {/* Lesson list */}
        <div>
          <div className="kicker" style={{ marginBottom: 10 }}>{t('module.lessons_count_kicker')} {lessonSet.lessons.length} {t('module.lessons_count_kicker_suffix')}</div>
          <h2 className="section-title" style={{ marginBottom: 20 }}>{t('module.what_you_learn')}</h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {lessonSet.lessons.map((les, i) => {
              const moduleDone = (data.user && data.user.completed || []).includes(moduleId);
              const isDone = moduleDone;
              const typeLabel = { read: t('module.lesson_type_read'), practice: t('module.lesson_type_practice'), quiz: t('module.lesson_type_quiz'), activity: t('module.lesson_type_activity') }[les.type];
              const typeColor = { read: 'sky', practice: 'sun', quiz: 'coral', activity: 'lavender' }[les.type];
              const typeIcon = { read: 'book', practice: 'sparkle', quiz: 'check', activity: 'zap' }[les.type];
              return (
                <button
                  key={i}
                  onClick={() => setActiveLesson(i)}
                  className="card"
                  style={{
                    padding: '16px 20px',
                    display: 'grid',
                    gridTemplateColumns: '40px 1fr auto auto',
                    alignItems: 'center',
                    gap: 16,
                    textAlign: 'left',
                    cursor: 'pointer',
                    transition: 'all 0.15s',
                    border: '1.5px solid var(--line)',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.borderColor = mainColor; }}
                  onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line)'; }}
                >
                  <div style={{
                    width: 36, height: 36, borderRadius: 10,
                    background: isDone ? mainColor : 'var(--bg-soft)',
                    color: isDone ? '#fff' : 'var(--ink-3)',
                    display: 'grid', placeItems: 'center',
                    fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 13,
                  }}>
                    {isDone ? <Icon name="check" size={16} /> : String(i + 1).padStart(2, '0')}
                  </div>
                  <div>
                    <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 2 }}>{les.title}</div>
                    <div className="row" style={{ gap: 10, fontSize: 12, color: 'var(--ink-3)' }}>
                      <span className="row" style={{ gap: 4 }}><Icon name="clock" size={11} />{les.duration}</span>
                      <span>·</span>
                      <span className={`chip chip-${typeColor}`} style={{ padding: '1px 8px', fontSize: 10 }}>{typeLabel}</span>
                    </div>
                  </div>
                  <div style={{ flex: 1 }} />
                  <Icon name="arrow" size={16} />
                </button>
              );
            })}
          </div>

          <button
            className="btn btn-accent"
            style={{ marginTop: 20, background: mainColor, width: '100%', justifyContent: 'center', padding: '14px 20px' }}
            onClick={() => setActiveLesson(lessonSet.lessons.findIndex(l => !l.done) !== -1 ? lessonSet.lessons.findIndex(l => !l.done) : 0)}
          >
            <Icon name="play" size={14} /> {t('module.continue_btn')}
          </button>
        </div>

        {/* Sidebar */}
        <aside style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div className="card" style={{ padding: 22 }}>
            <div className="kicker" style={{ marginBottom: 10 }}>{t('module.outcomes_kicker')}</div>
            <h3 style={{ fontSize: 16, marginBottom: 14 }}>{t('module.outcomes_title')}</h3>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {mod.outcomes.map((o, i) => (
                <li key={i} style={{ display: 'grid', gridTemplateColumns: '20px 1fr', gap: 10, fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.45 }}>
                  <span style={{ color: mainColor, marginTop: 2 }}><Icon name="check" size={14} /></span>
                  {o}
                </li>
              ))}
            </ul>
          </div>

          <div className="card" style={{ padding: 22 }}>
            <div className="kicker" style={{ marginBottom: 10 }}>{t('module.tools_kicker')}</div>
            <h3 style={{ fontSize: 16, marginBottom: 14 }}>{t('module.tools_title')}</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {mod.tools.map(toolName => {
                const tool = data.tools.find(x => x.name === toolName);
                const freeYes = tool && (tool.free === 'Evet' || tool.free === 'Yes');
                return (
                  <div key={toolName} className="row" style={{ justifyContent: 'space-between', padding: '10px 12px', background: 'var(--bg-soft)', borderRadius: 10 }}>
                    <div className="row" style={{ gap: 10 }}>
                      <div style={{
                        width: 28, height: 28, borderRadius: 8,
                        background: tool ? `var(--${tool.color})` : 'var(--ink-3)',
                        display: 'grid', placeItems: 'center', color: '#fff', fontWeight: 700, fontSize: 12,
                      }}>{toolName[0]}</div>
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{toolName}</div>
                        {tool && <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{freeYes ? t('module.tool_free_yes') : tool.free}</div>}
                      </div>
                    </div>
                    <Icon name="arrow" size={14} />
                  </div>
                );
              })}
            </div>
          </div>

          <div className="card" style={{ padding: 22, background: `linear-gradient(135deg, var(--${mod.color}-soft), transparent)` }}>
            <div className="kicker" style={{ marginBottom: 8 }}>{t('module.tip_kicker')}</div>
            <p style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>
              {t('module.tip_body_1')} <strong>{mod.duration}</strong> {t('module.tip_body_2')}
            </p>
          </div>
        </aside>
      </div>
    </div>
  );
}

// Ders içi görünüm (okuma + canlı prompt + quiz bir arada)
function LessonView({ mod, lesson, lessonIndex, totalLessons, onBack, onNext, onComplete }) {
  const colorMap = {
    moss: '#4F9D52', sun: '#F2A63B', coral: '#E86A4F',
    lavender: '#8A7AD1', sky: '#5CA5C7', rose: '#D6739A',
  };
  const mainColor = colorMap[mod.color];
  const pct = ((lessonIndex + 1) / totalLessons) * 100;
  const t = window.t;

  return (
    <div className="page fade-up" style={{ maxWidth: 920 }}>
      {/* Top bar */}
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 24 }}>
        <button onClick={onBack} className="btn btn-ghost btn-sm">
          <span style={{ display: 'inline-block', transform: 'rotate(180deg)' }}><Icon name="arrow" size={14} /></span> {t('lesson.back_to_module')}
        </button>
        <div className="row" style={{ gap: 10, fontSize: 13, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>
          <span>{t('lesson.lesson_x_of_y')} {lessonIndex + 1}/{totalLessons}</span>
          <div style={{ width: 120, height: 4, background: 'var(--bg-soft)', borderRadius: 2, overflow: 'hidden' }}>
            <div style={{ width: pct + '%', height: '100%', background: mainColor, borderRadius: 2 }} />
          </div>
        </div>
      </div>

      {/* Lesson header */}
      <div style={{ marginBottom: 28 }}>
        <div className="kicker" style={{ marginBottom: 10 }}>{mod.title.toUpperCase()}</div>
        <h1 style={{ fontSize: 40, letterSpacing: '-0.02em', marginBottom: 12 }}>{lesson.title}</h1>
        <div className="row" style={{ gap: 10, fontSize: 13, color: 'var(--ink-3)' }}>
          <span className="row" style={{ gap: 4 }}><Icon name="clock" size={13} />{lesson.duration}</span>
        </div>
      </div>

      {/* Content by type */}
      {lesson.type === 'read' && <ReadingContent mod={mod} lesson={lesson} color={mainColor} />}
      {lesson.type === 'practice' && <PracticeContent mod={mod} color={mainColor} />}
      {lesson.type === 'quiz' && <QuizContent onFinish={onComplete} color={mainColor} moduleId={mod.id} />}
      {lesson.type === 'activity' && <ActivityContent lesson={lesson} color={mainColor} />}

      {/* Nav footer */}
      {lesson.type !== 'quiz' && (
        <div className="row" style={{ justifyContent: 'space-between', marginTop: 40, paddingTop: 24, borderTop: '1px solid var(--line)' }}>
          <button className="btn btn-ghost btn-sm" onClick={onBack}>{t('lesson.back_to_module')}</button>
          <button className="btn" style={{ background: mainColor, color: '#fff' }} onClick={onNext}>
            {lessonIndex < totalLessons - 1 ? t('lesson.next_lesson') : t('lesson.finish_module')} <Icon name="arrow" size={14} />
          </button>
        </div>
      )}
    </div>
  );
}

function ReadingContent({ mod, lesson, color }) {
  const readings = (window.APP_DATA && window.APP_DATA.readings) || {};
  const t = window.t;
  const isEn = window.LANG === 'en';
  const content = readings[lesson.title] || {
    intro: t('lesson.placeholder_intro'),
    sections: isEn ? [
      { h: "Main idea", p: "Each module has 3-7 lessons. Lessons build on one another and end with a practice or short quiz to consolidate." },
      { h: "Tip", list: ["Follow the lesson order", "Don't skip live tries — that's where you learn most", "You can take notes from the side panel"] },
    ] : [
      { h: "Ana fikir", p: "Her modülde 3-7 ders bulunur. Dersler birbiri üzerine inşa edilir, sonunda bir uygulama veya kısa test ile pekişir." },
      { h: "İpucu", list: ["Ders sırasını takip edin", "Canlı denemeleri atlamayın — en çok orada öğrenirsiniz", "Notlarınızı sağdaki panelden alabilirsiniz"] },
    ],
    quote: t('lesson.placeholder_quote'),
  };

  return (
    <div>
      <p style={{ fontSize: 18, lineHeight: 1.65, color: 'var(--ink-2)', marginBottom: 32, fontFamily: 'var(--font-display)', fontWeight: 500, letterSpacing: '-0.01em' }}>
        {content.intro}
      </p>

      {content.sections.map((s, i) => {
        if (s.activity) {
          const activities = (window.APP_DATA && window.APP_DATA.activities) || {};
          const a = activities[s.activity];
          if (!a) return null;
          return <InlineActivity key={i} a={a} sectionTitle={s.h} color={color} />;
        }
        if (s.simulator) {
          const scenarios = (window.APP_DATA && window.APP_DATA.simulatorScenarios) || {};
          const sc = scenarios[s.simulator];
          if (!sc) return null;
          return (
            <div key={i} className="simulator-inline">
              {s.h && <h2 style={{ fontSize: 22, marginBottom: 8 }}>{s.h}</h2>}
              {s.p && <p style={{ fontSize: 15.5, lineHeight: 1.6, color: 'var(--ink-2)', marginBottom: 14 }}>{s.p}</p>}
              <ClaudeSimulator scenario={sc} color={color} />
            </div>
          );
        }
        return (
          <div key={i} style={{ marginBottom: 28 }}>
            {s.h && <h2 style={{ fontSize: 22, marginBottom: 12 }}>{s.h}</h2>}
            {s.p && <p style={{ fontSize: 16, lineHeight: 1.65, color: 'var(--ink-2)', whiteSpace: 'pre-wrap' }}>{s.p}</p>}
            {s.list && (
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
                {s.list.map((item, j) => (
                  <li key={j} style={{ display: 'grid', gridTemplateColumns: '24px 1fr', gap: 10, fontSize: 15.5, lineHeight: 1.55, color: 'var(--ink-2)' }}>
                    <span style={{ color, marginTop: 4, fontSize: 10 }}>●</span>
                    {item}
                  </li>
                ))}
              </ul>
            )}
            {s.prompt && <PromptBlock text={s.prompt} label={s.promptLabel} color={color} />}
            {s.mermaid && <MermaidBlock code={s.mermaid} />}
          </div>
        );
      })}

      {/* Pull-quote */}
      <div style={{
        borderLeft: `4px solid ${color}`,
        padding: '16px 24px',
        background: 'var(--bg-soft)',
        borderRadius: '0 var(--r-md) var(--r-md) 0',
        margin: '32px 0',
        fontFamily: 'var(--font-display)',
        fontSize: 22,
        lineHeight: 1.3,
        letterSpacing: '-0.01em',
      }}>
        "{content.quote}"
      </div>
    </div>
  );
}

// Canlı prompt denemesi — modüle göre şablon alır
function PracticeContent({ mod, color }) {
  const templates = (window.APP_DATA && window.APP_DATA.practiceTemplates) || {};
  const template = templates[mod.id] || templates[2];
  const t = window.t;

  const initialValues = {};
  (template.fields || []).forEach(f => { initialValues[f.key] = f.default || ""; });
  const [values, setValues] = useState(initialValues);
  const [generating, setGenerating] = useState(false);
  const [result, setResult] = useState(null);

  const promptText = template.buildPrompt(values);

  const handleGenerate = async () => {
    setGenerating(true);
    setResult(null);
    try {
      const response = await window.claude.complete(promptText);
      setResult(response);
    } catch (e) {
      setResult(template.fallback(values));
    }
    setGenerating(false);
  };

  const setField = (key, val) => setValues(prev => ({ ...prev, [key]: val }));

  return (
    <div>
      <div style={{
        background: `linear-gradient(135deg, var(--${mod.color}-soft), transparent)`,
        borderRadius: 'var(--r-lg)',
        padding: 20,
        marginBottom: 24,
        borderLeft: `4px solid ${color}`,
      }}>
        <div className="row" style={{ gap: 10, marginBottom: 8 }}>
          <Icon name="spark" size={16} />
          <strong style={{ fontSize: 14 }}>{template.title || t('practice.title_default')}</strong>
        </div>
        <p style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.5 }}>
          {template.intro || t('practice.intro_default')}
        </p>
      </div>

      {/* Input form */}
      <div className="card" style={{ padding: 24, marginBottom: 20 }}>
        <h3 style={{ fontSize: 17, marginBottom: 16 }}>{t('practice.step1_title')}</h3>
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.min(template.fields.length, 3)}, 1fr)`, gap: 14, marginBottom: 18 }}>
          {template.fields.map((f, i) => (
            <label key={f.key} style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 600 }}>{f.label}</span>
              <input
                type="text"
                value={values[f.key] || ''}
                onChange={e => setField(f.key, e.target.value)}
                placeholder={f.placeholder}
                style={{
                  padding: '10px 12px',
                  borderRadius: 10,
                  border: '1.5px solid var(--line)',
                  background: 'var(--bg)',
                  fontSize: 14,
                  fontFamily: 'inherit',
                  color: 'var(--ink)',
                }}
              />
            </label>
          ))}
        </div>
        <button className="btn" style={{ background: color, color: '#fff' }} onClick={handleGenerate} disabled={generating}>
          {generating ? t('practice.generating') : <><Icon name="sparkle" size={14} /> {t('practice.send_to_claude')}</>}
        </button>
      </div>

      {/* Prompt preview + result */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 16 }}>
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '12px 18px', background: 'var(--ink)', color: 'var(--bg)', fontSize: 12, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', fontWeight: 600 }}>
            {t('practice.prompt_caps')}
          </div>
          <pre style={{
            padding: 18, margin: 0,
            fontFamily: 'var(--font-mono)', fontSize: 12.5,
            color: 'var(--ink-2)',
            whiteSpace: 'pre-wrap', lineHeight: 1.6,
            overflowX: 'auto',
          }}>{promptText}</pre>
        </div>
        <div className="card" style={{ padding: 0, overflow: 'hidden', background: 'var(--bg-soft)' }}>
          <div style={{ padding: '12px 18px', background: color, color: '#fff', fontSize: 12, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', fontWeight: 600 }}>
            {t('practice.output_caps')}
          </div>
          <div style={{ padding: 18, fontSize: 13.5, lineHeight: 1.65, color: 'var(--ink-2)', minHeight: 280, whiteSpace: 'pre-wrap' }}>
            {generating ? (
              <span style={{ color: 'var(--ink-3)' }}>
                <span style={{ animation: 'pulse 1.2s infinite' }}>●</span> {t('practice.generating_msg')}
              </span>
            ) : result || <span style={{ color: 'var(--ink-3)' }}>{t('practice.placeholder_press')}</span>}
          </div>
        </div>
      </div>
    </div>
  );
}

function QuizContent({ onFinish, color, moduleId }) {
  const banks = (window.APP_DATA && window.APP_DATA.moduleQuizzes) || {};
  const qs = banks[moduleId] || window.APP_DATA.quizQuestions;
  const [idx, setIdx] = useState(0);
  const [picked, setPicked] = useState(null);
  const [revealed, setRevealed] = useState(false);
  const [score, setScore] = useState(0);
  const [done, setDone] = useState(false);
  const t = window.t;
  const isEn = window.LANG === 'en';

  const q = qs[idx];

  const pick = (i) => {
    if (revealed) return;
    setPicked(i);
    setRevealed(true);
    if (i === q.correct) setScore(s => s + 1);
  };

  const next = () => {
    if (idx < qs.length - 1) {
      setIdx(idx + 1);
      setPicked(null);
      setRevealed(false);
    } else {
      setDone(true);
    }
  };

  if (done) {
    const pct = Math.round((score / qs.length) * 100);
    const passed = pct >= 67;
    return (
      <div className="card fade-up" style={{ padding: 40, textAlign: 'center' }}>
        <div style={{ fontSize: 72, marginBottom: 16 }}>{passed ? '🎉' : '🌱'}</div>
        <h2 style={{ fontSize: 32, marginBottom: 8 }}>{passed ? t('quiz.great_job') : t('quiz.try_again_title')}</h2>
        <p style={{ fontSize: 16, color: 'var(--ink-2)', marginBottom: 24 }}>
          {isEn ? (
            <>{t('quiz.score_intro_1')} <strong>{score}</strong> {t('quiz.score_intro_2')} {qs.length}. ({pct}%)</>
          ) : (
            <>{qs.length} {t('quiz.score_intro_1')} <strong>{score}</strong>{t('quiz.score_intro_2')} (%{pct})</>
          )}
        </p>
        <div style={{ width: 300, height: 10, background: 'var(--bg-soft)', borderRadius: 5, margin: '0 auto 32px', overflow: 'hidden' }}>
          <div style={{ width: pct + '%', height: '100%', background: passed ? color : 'var(--sun)', borderRadius: 5, transition: 'width 0.5s' }} />
        </div>
        <div className="row" style={{ gap: 10, justifyContent: 'center' }}>
          <button className="btn btn-ghost btn-sm" onClick={() => { setIdx(0); setPicked(null); setRevealed(false); setScore(0); setDone(false); }}>
            <Icon name="restart" size={14} /> {t('quiz.try_again_btn')}
          </button>
          <button className="btn" style={{ background: color, color: '#fff' }} onClick={() => onFinish && onFinish()}>
            {t('quiz.finish_module')} <Icon name="check" size={14} />
          </button>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
        <span className="kicker">{t('quiz.question')} {idx + 1}/{qs.length}</span>
        <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>{t('quiz.correct_count')}: <strong>{score}</strong></span>
      </div>

      <div className="card" style={{ padding: 32 }}>
        <h2 style={{ fontSize: 22, marginBottom: 22, lineHeight: 1.3 }}>{q.q}</h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {q.options.map((opt, i) => {
            const isCorrect = i === q.correct;
            const isPicked = i === picked;
            let bg = 'var(--bg)', bd = 'var(--line)', fg = 'var(--ink)';
            if (revealed) {
              if (isCorrect) { bg = 'var(--moss-soft)'; bd = 'var(--moss)'; fg = 'var(--moss-deep)'; }
              else if (isPicked) { bg = 'var(--coral-soft)'; bd = 'var(--coral)'; fg = '#9B3520'; }
            }
            return (
              <button
                key={i}
                onClick={() => pick(i)}
                style={{
                  padding: '14px 18px',
                  borderRadius: 12,
                  border: `1.5px solid ${bd}`,
                  background: bg,
                  color: fg,
                  textAlign: 'left',
                  cursor: revealed ? 'default' : 'pointer',
                  fontSize: 15,
                  fontWeight: 500,
                  transition: 'all 0.15s',
                  display: 'grid',
                  gridTemplateColumns: '28px 1fr auto',
                  alignItems: 'center',
                  gap: 12,
                }}
              >
                <span style={{
                  width: 24, height: 24, borderRadius: 6,
                  background: revealed && isCorrect ? 'var(--moss)' : revealed && isPicked ? 'var(--coral)' : 'var(--bg-soft)',
                  color: revealed && (isCorrect || isPicked) ? '#fff' : 'var(--ink-3)',
                  display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 12, fontFamily: 'var(--font-mono)',
                }}>{String.fromCharCode(65 + i)}</span>
                <span>{opt}</span>
                {revealed && isCorrect && <Icon name="check" size={16} />}
              </button>
            );
          })}
        </div>

        {revealed && (
          <div className="fade-up" style={{
            marginTop: 20, padding: 16,
            background: 'var(--bg-soft)',
            borderRadius: 12,
            fontSize: 14,
            color: 'var(--ink-2)',
            lineHeight: 1.55,
            borderLeft: `4px solid ${color}`,
          }}>
            <strong>{t('quiz.explanation')}</strong> {q.explain}
          </div>
        )}

        {revealed && (
          <div style={{ marginTop: 20, textAlign: 'right' }}>
            <button className="btn" style={{ background: color, color: '#fff' }} onClick={next}>
              {idx < qs.length - 1 ? t('common.next_question') : t('common.see_results')} <Icon name="arrow" size={14} />
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

function PromptBlock({ text, label, color }) {
  const [copied, setCopied] = useState(false);
  const tt = window.t;
  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    } catch (e) {
      const ta = document.createElement('textarea');
      ta.value = text;
      document.body.appendChild(ta);
      ta.select();
      try { document.execCommand('copy'); setCopied(true); setTimeout(() => setCopied(false), 1800); } catch(_){}
      document.body.removeChild(ta);
    }
  };
  return (
    <div style={{
      marginTop: 14,
      borderRadius: 'var(--r-md)',
      border: `1.5px solid var(--line)`,
      background: 'var(--bg)',
      overflow: 'hidden',
    }}>
      <div className="row" style={{
        padding: '8px 12px 8px 14px',
        background: 'var(--bg-soft)',
        borderBottom: '1px solid var(--line)',
        justifyContent: 'space-between',
        alignItems: 'center',
      }}>
        <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', letterSpacing: '0.1em', fontWeight: 600 }}>
          {(label || 'PROMPT').toUpperCase()}
        </span>
        <button
          onClick={handleCopy}
          style={{
            background: copied ? color : 'transparent',
            color: copied ? '#fff' : 'var(--ink-2)',
            border: `1px solid ${copied ? color : 'var(--line-strong)'}`,
            borderRadius: 6,
            padding: '4px 10px',
            fontSize: 11,
            fontWeight: 600,
            cursor: 'pointer',
            fontFamily: 'inherit',
            transition: 'all 0.15s',
          }}
        >
          {copied ? (window.LANG === 'en' ? '✓ Copied' : '✓ Kopyalandı') : (window.LANG === 'en' ? 'Copy' : 'Kopyala')}
        </button>
      </div>
      <pre style={{
        margin: 0,
        padding: '14px 16px',
        fontFamily: 'var(--font-mono)',
        fontSize: 13,
        lineHeight: 1.6,
        color: 'var(--ink)',
        whiteSpace: 'pre-wrap',
        wordBreak: 'break-word',
      }}>{text}</pre>
    </div>
  );
}

function MermaidBlock({ code }) {
  const ref = useRef(null);
  const idRef = useRef('mmd-' + Math.random().toString(36).slice(2, 9));

  useEffect(() => {
    let cancelled = false;
    const render = async () => {
      if (!window.mermaid) {
        // Kütüphane yüklenmediyse 50ms aralıklarla bekle (max 3sn)
        for (let i = 0; i < 60; i++) {
          await new Promise(r => setTimeout(r, 50));
          if (window.mermaid) break;
        }
      }
      if (cancelled || !ref.current || !window.mermaid) return;
      try {
        const { svg } = await window.mermaid.render(idRef.current, code);
        if (!cancelled && ref.current) ref.current.innerHTML = svg;
      } catch (err) {
        if (ref.current) ref.current.innerHTML = `<div style="color:var(--ink-3);font-size:13px">${window.t('diagram.failed')}</div>`;
      }
    };
    render();
    return () => { cancelled = true; };
  }, [code]);

  return (
    <div style={{
      marginTop: 14,
      padding: 20,
      borderRadius: 'var(--r-md)',
      background: 'var(--bg-elevated)',
      border: '1px solid var(--line)',
      display: 'grid',
      placeItems: 'center',
      overflowX: 'auto',
    }}>
      <div ref={ref} style={{ width: '100%', textAlign: 'center' }}>
        <div style={{ color: 'var(--ink-3)', fontSize: 13, padding: 12 }}>{window.t('diagram.loading')}</div>
      </div>
    </div>
  );
}

function InlineActivity({ a, sectionTitle, color }) {
  const t = window.t;
  const typeLabel = { compare: t('activity.compare_label'), predict: t('activity.predict_label'), sort: t('activity.sort_label') }[a.type] || t('activity.activity_label');
  return (
    <div style={{
      margin: '36px 0',
      borderRadius: 'var(--r-lg)',
      border: '2px dashed var(--lavender)',
      background: `linear-gradient(135deg, var(--lavender-soft)55 0%, transparent 60%)`,
      padding: 28,
      position: 'relative',
    }}>
      <div className="row" style={{ gap: 10, marginBottom: 8 }}>
        <div style={{
          width: 32, height: 32, borderRadius: 8,
          background: 'var(--lavender)',
          display: 'grid', placeItems: 'center', color: '#fff',
        }}>
          <Icon name="zap" size={16} />
        </div>
        <div>
          <div style={{ fontSize: 11, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', color: 'var(--ink-3)', fontWeight: 700 }}>
            {t('activity.now_you')} · {typeLabel}
          </div>
          {sectionTitle && <div style={{ fontSize: 16, fontWeight: 700, marginTop: 2 }}>{sectionTitle}</div>}
        </div>
      </div>
      <p style={{ fontSize: 14.5, color: 'var(--ink-2)', lineHeight: 1.55, marginBottom: 18, marginTop: 8 }}>{a.intro}</p>

      {a.type === 'compare' && <CompareCard a={a} color={color} />}
      {a.type === 'predict' && <PredictCard a={a} color={color} />}
      {a.type === 'sort' && <SortCard a={a} color={color} />}
      {a.type === 'simulator' && <ClaudeSimulator scenario={a} color={color} />}
    </div>
  );
}

function ActivityContent({ lesson, color }) {
  const activities = (window.APP_DATA && window.APP_DATA.activities) || {};
  const a = activities[lesson.title];
  const t = window.t;

  if (!a) {
    return (
      <div style={{ padding: 24, background: 'var(--bg-soft)', borderRadius: 'var(--r-md)', color: 'var(--ink-3)' }}>
        {t('activity.preparing')}
      </div>
    );
  }

  return (
    <div>
      <div style={{
        background: `linear-gradient(135deg, var(--lavender-soft), transparent)`,
        borderRadius: 'var(--r-lg)',
        padding: 20,
        marginBottom: 24,
        borderLeft: `4px solid ${color}`,
      }}>
        <div className="row" style={{ gap: 10, marginBottom: 8 }}>
          <Icon name="zap" size={16} />
          <strong style={{ fontSize: 14, fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>
            {t('activity.activity_label')} · {({ compare: t('activity.compare_label'), predict: t('activity.predict_label'), sort: t('activity.sort_label') })[a.type] || ''}
          </strong>
        </div>
        <p style={{ fontSize: 14.5, color: 'var(--ink-2)', lineHeight: 1.55 }}>{a.intro}</p>
      </div>

      {a.type === 'compare' && <CompareCard a={a} color={color} />}
      {a.type === 'predict' && <PredictCard a={a} color={color} />}
      {a.type === 'sort' && <SortCard a={a} color={color} />}
      {a.type === 'simulator' && <ClaudeSimulator scenario={a} color={color} />}
    </div>
  );
}

function CompareCard({ a, color }) {
  const [picked, setPicked] = useState(null);
  const t = window.t;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
        {a.options.map((opt, i) => {
          const isPicked = picked === i;
          const isCorrect = opt.isCorrect;
          const showState = picked !== null;
          const borderColor = !showState ? 'var(--line)'
            : isPicked && isCorrect ? '#4F9D52'
            : isPicked && !isCorrect ? '#E86A4F'
            : !isPicked && isCorrect ? '#4F9D52'
            : 'var(--line)';
          const bg = !showState ? 'var(--bg-elevated)'
            : isPicked && isCorrect ? 'rgba(79,157,82,0.06)'
            : isPicked && !isCorrect ? 'rgba(232,106,79,0.06)'
            : !isPicked && isCorrect ? 'rgba(79,157,82,0.06)'
            : 'var(--bg-elevated)';
          return (
            <button
              key={i}
              onClick={() => picked === null && setPicked(i)}
              disabled={picked !== null}
              className="card"
              style={{
                padding: 18,
                textAlign: 'left',
                cursor: picked === null ? 'pointer' : 'default',
                border: `2px solid ${borderColor}`,
                background: bg,
                transition: 'all 0.15s',
                display: 'flex',
                flexDirection: 'column',
                gap: 10,
              }}
            >
              <div className="row" style={{ justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', fontWeight: 700, color: 'var(--ink-3)' }}>
                  {t('activity.option_caps')} {opt.label}
                </span>
                {showState && isCorrect && <span style={{ color: '#4F9D52', fontSize: 18 }}>✓</span>}
                {showState && isPicked && !isCorrect && <span style={{ color: '#E86A4F', fontSize: 18 }}>✕</span>}
              </div>
              <pre style={{
                margin: 0,
                fontFamily: 'var(--font-mono)',
                fontSize: 13,
                lineHeight: 1.55,
                color: 'var(--ink-2)',
                whiteSpace: 'pre-wrap',
                wordBreak: 'break-word',
              }}>{opt.text}</pre>
            </button>
          );
        })}
      </div>

      {picked !== null && (
        <div style={{
          marginTop: 20,
          padding: 18,
          borderRadius: 'var(--r-md)',
          background: 'var(--bg-soft)',
          borderLeft: `4px solid ${color}`,
        }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', fontWeight: 700, color: 'var(--ink-3)', marginBottom: 8 }}>
            {a.options[picked].isCorrect ? t('activity.correct_kicker') : t('activity.wrong_kicker')}
          </div>
          <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink)' }}>
            {a.options[picked].isCorrect ? a.explanationCorrect : a.explanationWrong}
          </p>
          {!a.options[picked].isCorrect && (
            <button
              onClick={() => setPicked(null)}
              className="btn btn-ghost btn-sm"
              style={{ marginTop: 12 }}
            >{t('activity.try_again')}</button>
          )}
        </div>
      )}
    </div>
  );
}

function PredictCard({ a, color }) {
  const [guess, setGuess] = useState('');
  const [revealed, setRevealed] = useState(false);
  const t = window.t;

  return (
    <div>
      <div style={{ marginBottom: 18 }}>
        <div className="kicker" style={{ marginBottom: 8 }}>{t('activity.given_prompt')}</div>
        <PromptBlock text={a.prompt} label="PROMPT" color={color} />
      </div>

      <div style={{ marginBottom: 18 }}>
        <div className="kicker" style={{ marginBottom: 8 }}>{t('activity.your_guess')}</div>
        <textarea
          value={guess}
          onChange={e => setGuess(e.target.value)}
          disabled={revealed}
          placeholder={a.hint || t('activity.guess_placeholder')}
          rows={4}
          style={{
            width: '100%',
            padding: 14,
            borderRadius: 'var(--r-md)',
            border: '1.5px solid var(--line-strong)',
            fontFamily: 'inherit',
            fontSize: 14,
            lineHeight: 1.55,
            background: revealed ? 'var(--bg-soft)' : 'var(--bg-elevated)',
            color: 'var(--ink)',
            outline: 'none',
            resize: 'vertical',
          }}
        />
      </div>

      {!revealed ? (
        <button
          onClick={() => setRevealed(true)}
          disabled={guess.trim().length < 10}
          className="btn"
          style={{
            background: guess.trim().length < 10 ? 'var(--bg-soft)' : color,
            color: guess.trim().length < 10 ? 'var(--ink-3)' : '#fff',
            cursor: guess.trim().length < 10 ? 'not-allowed' : 'pointer',
          }}
        >
          <Icon name="sparkle" size={14} /> {t('activity.show_real')}
        </button>
      ) : (
        <div>
          <div className="kicker" style={{ marginBottom: 8 }}>{t('activity.real_answer')}</div>
          <div style={{
            padding: 18,
            borderRadius: 'var(--r-md)',
            background: 'var(--bg-elevated)',
            border: `1.5px solid ${color}`,
            fontSize: 15,
            lineHeight: 1.6,
            color: 'var(--ink)',
            whiteSpace: 'pre-wrap',
          }}>{a.realResponse}</div>

          {a.takeaway && (
            <div style={{
              marginTop: 16,
              padding: 16,
              borderRadius: 'var(--r-md)',
              background: 'var(--bg-soft)',
              borderLeft: `4px solid ${color}`,
            }}>
              <div className="kicker" style={{ marginBottom: 6 }}>{t('activity.takeaway_kicker')}</div>
              <p style={{ fontSize: 14, lineHeight: 1.6 }}>{a.takeaway}</p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function SortCard({ a, color }) {
  const t = window.t;
  const shuffled = useMemo(() => {
    const arr = [...a.items];
    for (let i = arr.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
  }, [a]);

  const [order, setOrder] = useState(shuffled);
  const [checked, setChecked] = useState(false);

  const move = (idx, dir) => {
    if (checked) return;
    const next = [...order];
    const swap = idx + dir;
    if (swap < 0 || swap >= next.length) return;
    [next[idx], next[swap]] = [next[swap], next[idx]];
    setOrder(next);
  };

  const isAllCorrect = checked && order.every((it, i) => it.correctOrder === i + 1);

  return (
    <div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 18 }}>
        {order.map((item, i) => {
          const correctHere = checked && item.correctOrder === i + 1;
          const wrongHere = checked && item.correctOrder !== i + 1;
          return (
            <div
              key={item.id}
              className="card"
              style={{
                padding: '14px 18px',
                display: 'grid',
                gridTemplateColumns: '40px 1fr auto',
                alignItems: 'center',
                gap: 14,
                border: `2px solid ${correctHere ? '#4F9D52' : wrongHere ? '#E86A4F' : 'var(--line)'}`,
                background: correctHere ? 'rgba(79,157,82,0.06)' : wrongHere ? 'rgba(232,106,79,0.06)' : 'var(--bg-elevated)',
                transition: 'all 0.15s',
              }}
            >
              <div style={{
                width: 32, height: 32, borderRadius: 8,
                background: 'var(--bg-soft)',
                display: 'grid', placeItems: 'center',
                fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 13,
                color: 'var(--ink-3)',
              }}>{i + 1}</div>
              <div style={{ fontSize: 14.5, lineHeight: 1.5 }}>
                {item.label && (
                  <strong style={{ display: 'block', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', color: 'var(--ink-3)', marginBottom: 3 }}>
                    {item.label}
                  </strong>
                )}
                {item.text}
              </div>
              <div className="row" style={{ gap: 4 }}>
                <button
                  onClick={() => move(i, -1)}
                  disabled={i === 0 || checked}
                  style={{
                    width: 30, height: 30, borderRadius: 8,
                    border: '1px solid var(--line)',
                    background: 'var(--bg)',
                    cursor: i === 0 || checked ? 'not-allowed' : 'pointer',
                    opacity: i === 0 || checked ? 0.4 : 1,
                  }}
                  aria-label={t('activity.move_up')}
                >↑</button>
                <button
                  onClick={() => move(i, 1)}
                  disabled={i === order.length - 1 || checked}
                  style={{
                    width: 30, height: 30, borderRadius: 8,
                    border: '1px solid var(--line)',
                    background: 'var(--bg)',
                    cursor: i === order.length - 1 || checked ? 'not-allowed' : 'pointer',
                    opacity: i === order.length - 1 || checked ? 0.4 : 1,
                  }}
                  aria-label={t('activity.move_down')}
                >↓</button>
              </div>
            </div>
          );
        })}
      </div>

      {!checked ? (
        <button
          onClick={() => setChecked(true)}
          className="btn"
          style={{ background: color, color: '#fff' }}
        >
          <Icon name="check" size={14} /> {t('activity.check_order')}
        </button>
      ) : (
        <div style={{
          padding: 18,
          borderRadius: 'var(--r-md)',
          background: isAllCorrect ? 'rgba(79,157,82,0.08)' : 'var(--bg-soft)',
          borderLeft: `4px solid ${isAllCorrect ? '#4F9D52' : color}`,
        }}>
          <div className="kicker" style={{ marginBottom: 8 }}>
            {isAllCorrect ? t('activity.perfect_kicker') : t('activity.partial_kicker')}
          </div>
          <p style={{ fontSize: 14, lineHeight: 1.6, marginBottom: 12 }}>{a.explanation}</p>
          {!isAllCorrect && (
            <button
              onClick={() => { setOrder(shuffled); setChecked(false); }}
              className="btn btn-ghost btn-sm"
            >{t('activity.retry')}</button>
          )}
        </div>
      )}
    </div>
  );
}

// =====================================================================
// Claude UI Simülatörü — gerçek claude.ai arayüzünü taklit eden
// rehberli interaktif demo. Senaryo `a` objesinde tanımlanır.
// =====================================================================
function SimIcon({ name, size = 16 }) {
  const c = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const paths = {
    plus:       <><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></>,
    search:     <><circle cx="11" cy="11" r="7"/><line x1="20" y1="20" x2="16.65" y2="16.65"/></>,
    chats:      <><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></>,
    projects:   <><path d="M3 7a2 2 0 0 1 2-2h4l2 3h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></>,
    code:       <><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></>,
    customize:  <><line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/><line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/><line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/><line x1="1" y1="14" x2="7" y2="14"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="17" y1="16" x2="23" y2="16"/></>,
    design:     <><circle cx="13.5" cy="6.5" r="1.4"/><circle cx="17.5" cy="10.5" r="1.4"/><circle cx="8.5" cy="7.5" r="1.4"/><circle cx="6.5" cy="12.5" r="1.4"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c1 0 1.5-.7 1.5-1.5 0-.4-.2-.8-.5-1.1-.3-.3-.5-.6-.5-1 0-.8.7-1.5 1.5-1.5H16c3.3 0 6-2.7 6-6 0-5-4.5-9-10-9z"/></>,
    chevDown:   <><polyline points="6 9 12 15 18 9"/></>,
    pencil:     <><path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4z"/></>,
    grad:       <><path d="M22 10 12 5 2 10l10 5 10-5z"/><path d="M6 12v5c0 1.7 2.7 3 6 3s6-1.3 6-3v-5"/></>,
    coffee:     <><path d="M17 8h1a4 4 0 0 1 0 8h-1"/><path d="M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4z"/><line x1="6" y1="2" x2="6" y2="5"/><line x1="10" y1="2" x2="10" y2="5"/><line x1="14" y1="2" x2="14" y2="5"/></>,
    drive:      <><polygon points="7.5 3 16.5 3 21 11 12 11"/><polygon points="3 14 12 14 7.5 22 3 14"/><polygon points="12 14 21 14 16.5 22 12 22"/></>,
    arrowUp:    <><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></>,
    arrowDown:  <><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></>,
    arrowExt:   <><path d="M7 17 17 7"/><polyline points="7 7 17 7 17 17"/></>,
    lock:       <><rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></>,
    pin:        <><line x1="12" y1="17" x2="12" y2="22"/><path d="M9 4h6l-1 7 3 3H7l3-3z"/></>,
    sidebar:    <><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="3" x2="9" y2="21"/></>,
    help:       <><circle cx="12" cy="12" r="10"/><path d="M9.1 9a3 3 0 0 1 5.8 1c0 2-3 2.5-3 4.5"/><line x1="12" y1="18" x2="12.01" y2="18"/></>,
  };
  return <svg {...c}>{paths[name]}</svg>;
}

// Claude'un turuncu ✦ marka ikonu — özel SVG (8-point asterisk)
function ClaudeMark({ size = 18, color = '#D97757' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={color} aria-hidden="true">
      <path d="M12 2c.4 3.6 1.5 5.7 3.4 6.6-1.9.9-3 3-3.4 6.6-.4-3.6-1.5-5.7-3.4-6.6 1.9-.9 3-3 3.4-6.6zm0 11c.3 2.7 1.1 4.3 2.5 5-1.4.7-2.2 2.3-2.5 5-.3-2.7-1.1-4.3-2.5-5 1.4-.7 2.2-2.3 2.5-5z"/>
    </svg>
  );
}

function ClaudeSimulator({ scenario, color }) {
  const isEn = window.LANG === 'en';
  const STR = isEn ? {
    demo: 'DEMO',
    badgeNote: 'This is a simulation. Visit claude.ai for the real Claude.',
    newChat: 'New chat',
    search: 'Search',
    chats: 'Chats',
    projects: 'Projects',
    code: 'Code',
    customize: 'Customize',
    design: 'Design',
    more: 'More',
    starred: 'Starred',
    recents: 'Recents',
    placeholder: 'How can I help you today?',
    write: 'Write',
    learn: 'Learn',
    codeBtn: 'Code',
    lifeStuff: 'Life stuff',
    fromDrive: 'From Drive',
    suggested: 'Try this prompt',
    paste: 'Paste',
    typing: 'Claude is typing',
    stepHint: 'Hint',
    next: 'Continue',
    restart: 'Try again',
    finalTitle: 'Nice — you sent your first prompt!',
    finalBody: 'When you\'re ready, log into claude.ai and try it for real.',
    openClaude: 'Open claude.ai',
    you: 'You',
    youInitials: 'YO',
    promptsLeft: 'characters',
  } : {
    demo: 'DEMO',
    badgeNote: 'Bu bir simülasyondur. Gerçek Claude için claude.ai\'ı ziyaret edin.',
    newChat: 'Yeni sohbet',
    search: 'Arama',
    chats: 'Sohbetler',
    projects: 'Projeler',
    code: 'Kod',
    customize: 'Özelleştir',
    design: 'Tasarım',
    more: 'Daha fazla',
    starred: 'Yıldızlı',
    recents: 'Son sohbetler',
    placeholder: 'Bugün size nasıl yardımcı olabilirim?',
    write: 'Yaz',
    learn: 'Öğren',
    codeBtn: 'Kod',
    lifeStuff: 'Günlük',
    fromDrive: 'Drive\'dan',
    suggested: 'Önerilen prompt',
    paste: 'Yapıştır',
    typing: 'Claude yazıyor',
    stepHint: 'İpucu',
    next: 'Devam et',
    restart: 'Yeniden dene',
    finalTitle: 'Tebrikler — ilk prompt\'unuzu attınız!',
    finalBody: 'Hazır olduğunuzda claude.ai\'a girip gerçek deneyimi yaşayın.',
    openClaude: 'claude.ai\'ı aç',
    you: 'Siz',
    youInitials: 'BN',
    promptsLeft: 'karakter',
  };

  const mode = scenario.mode || 'interactive'; // 'auto' | 'mixed' | 'interactive'
  const suggestedPrompt = scenario.suggestedPrompt || (isEn
    ? 'You are an experienced 4th-grade teacher. Prepare 5 fraction-addition exercises at three difficulty levels (basic / intermediate / advanced). Output as a Markdown table with columns: difficulty | question | answer.'
    : 'Sen deneyimli bir 4. sınıf öğretmenisin. Üç zorluk seviyesinde (temel / orta / ileri) toplam 5 kesir toplama sorusu hazırla. Çıktıyı Markdown tablo halinde ver: zorluk | soru | cevap.');

  const pickResponse = (text) => {
    const lower = (text || '').toLowerCase();
    if (scenario.scriptedResponses) {
      for (const r of scenario.scriptedResponses) {
        if (r.match.some(kw => lower.includes(kw.toLowerCase()))) return r.text;
      }
    }
    if (lower.includes('kesir') || lower.includes('fraction')) {
      return isEn
        ? `Here are 5 fraction-addition exercises across three levels:\n\n| Difficulty | Question | Answer |\n|---|---|---|\n| Basic | 1/4 + 2/4 = ? | 3/4 |\n| Basic | 2/5 + 1/5 = ? | 3/5 |\n| Intermediate | 1/3 + 1/6 = ? | 1/2 |\n| Intermediate | 2/3 + 1/4 = ? | 11/12 |\n| Advanced | 1/2 + 2/5 + 1/10 = ? | 1 |\n\n**Teaching tip:** start with same-denominator items so students build confidence; then introduce LCM with the intermediate questions.`
        : `İşte üç seviyede 5 kesir toplama sorusu:\n\n| Zorluk | Soru | Cevap |\n|---|---|---|\n| Temel | 1/4 + 2/4 = ? | 3/4 |\n| Temel | 2/5 + 1/5 = ? | 3/5 |\n| Orta | 1/3 + 1/6 = ? | 1/2 |\n| Orta | 2/3 + 1/4 = ? | 11/12 |\n| İleri | 1/2 + 2/5 + 1/10 = ? | 1 |\n\n**Öğretim ipucu:** Önce aynı paydalı sorularla güveni kurun; orta seviyede EKOK kavramını tanıtın.`;
    }
    return isEn
      ? `That\'s a great start! In real Claude you\'d see a fully tailored answer. Try the suggested prompt or replay the demo to see structure tricks (role + context + format) in action.`
      : `Güzel bir başlangıç! Gerçek Claude'da size özel hazırlanmış bir yanıt çıkardı. Önerilen prompt'u deneyin ya da demoyu tekrar izleyip yapı hilelerini (rol + bağlam + format) görün.`;
  };

  // ===== State =====
  const [text, setText] = useState('');
  const [conversation, setConversation] = useState([]);
  const [done, setDone] = useState(false);
  const [cursor, setCursor] = useState({ x: -200, y: -200, visible: false, clicking: false });
  const [tooltip, setTooltip] = useState(null);
  const [highlights, setHighlights] = useState({});
  const [modelOpen, setModelOpen] = useState(false);
  const [selectedModel, setSelectedModel] = useState(scenario.startModel || 'Sonnet 4.6');
  const [stepIdx, setStepIdx] = useState(0);
  const [playing, setPlaying] = useState(false);
  const [waitingFor, setWaitingFor] = useState(null);
  const [hasRun, setHasRun] = useState(false);
  const [attachedFiles, setAttachedFiles] = useState([]); // [{name, kind, html}]

  // ===== Refs =====
  const wrapperRef = useRef(null);
  const inputRef = useRef(null);
  const scrollRef = useRef(null);
  const streamTimer = useRef(null);
  const versionRef = useRef(0);
  const userResolveRef = useRef(null);
  const refsObj = useRef({}).current;
  const setRef = (name) => (el) => { if (el) refsObj[name] = el; };

  // ===== Engine helpers =====
  const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  const isStale = (v) => versionRef.current !== v;

  // Conditionally rendered targets (dropdown items) populate refs only
  // after React commits the render. Wait up to 1s for the ref to appear.
  const waitForRef = async (target, version, maxAttempts = 20) => {
    for (let i = 0; i < maxAttempts; i++) {
      if (refsObj[target]) return refsObj[target];
      if (isStale(version)) return null;
      await sleep(50);
    }
    return refsObj[target] || null;
  };

  const moveCursorTo = async (target, version) => {
    const el = await waitForRef(target, version);
    const wrap = wrapperRef.current;
    if (!el || !wrap) { await sleep(120); return; }
    const er = el.getBoundingClientRect();
    const wr = wrap.getBoundingClientRect();
    const x = er.left - wr.left + er.width / 2;
    const y = er.top - wr.top + er.height / 2;
    setCursor(c => ({ ...c, x, y, visible: true }));
    await sleep(720);
    if (isStale(version)) return;
  };

  const clickPulse = async (target, version) => {
    setCursor(c => ({ ...c, clicking: true }));
    if (target) setHighlights(h => ({ ...h, [target]: 'click' }));
    await sleep(220);
    if (isStale(version)) return;
    setCursor(c => ({ ...c, clicking: false }));
    if (target) setHighlights(h => { const n = { ...h }; delete n[target]; return n; });
  };

  const typewrite = async (str, version, speed = 32) => {
    for (let i = 1; i <= str.length; i++) {
      if (isStale(version)) return;
      setText(str.slice(0, i));
      const ch = str.charAt(i - 1);
      const extra = (ch === ' ' ? 0 : Math.random() * 30) + ((ch === '.' || ch === ',' || ch === '\n') ? 80 : 0);
      await sleep(speed + extra);
    }
  };

  const sendMessage = async (overrideResp, version) => {
    const trimmed = (text || '').trim();
    if (!trimmed && attachedFiles.length === 0) return;
    const attachments = attachedFiles;
    setConversation([{ role: 'user', content: trimmed, attachments }, { role: 'assistant', content: '', streaming: true }]);
    setText('');
    setAttachedFiles([]);
    const full = overrideResp || pickResponse(trimmed);
    await new Promise((resolve) => {
      if (streamTimer.current) clearInterval(streamTimer.current);
      let i = 0;
      streamTimer.current = setInterval(() => {
        if (isStale(version)) { clearInterval(streamTimer.current); resolve(); return; }
        i += Math.max(2, Math.floor(full.length / 110));
        if (i >= full.length) {
          setConversation([{ role: 'user', content: trimmed }, { role: 'assistant', content: full, streaming: false }]);
          clearInterval(streamTimer.current);
          streamTimer.current = null;
          resolve();
          return;
        }
        setConversation([{ role: 'user', content: trimmed }, { role: 'assistant', content: full.slice(0, i), streaming: true }]);
      }, 28);
    });
  };

  const awaitUserAction = (action, hint) => {
    setWaitingFor({ action, hint });
    return new Promise(resolve => { userResolveRef.current = { action, resolve }; });
  };

  const reportUserAction = (action) => {
    const r = userResolveRef.current;
    if (r && r.action === action) {
      userResolveRef.current = null;
      setWaitingFor(null);
      r.resolve();
    }
  };

  const runStep = async (step, version) => {
    if (isStale(version)) return;
    switch (step.type) {
      case 'cursor_to':
        await moveCursorTo(step.target, version);
        break;
      case 'click':
        if (step.target) await clickPulse(step.target, version);
        if (step.then === 'open_model') setModelOpen(true);
        if (step.then === 'close_model') setModelOpen(false);
        break;
      case 'open_model':
        setModelOpen(true); await sleep(280); break;
      case 'select_model':
        setSelectedModel(step.value); setModelOpen(false); await sleep(260); break;
      case 'close_model':
        setModelOpen(false); await sleep(220); break;
      case 'type':
        await typewrite(step.text, version, step.speed || 32);
        break;
      case 'set_input':
        setText(step.text); await sleep(120); break;
      case 'clear_input':
        setText(''); await sleep(120); break;
      case 'send':
        await sendMessage(step.response, version); break;
      case 'tooltip':
        if (step.target) {
          await waitForRef(step.target, version);
          if (isStale(version)) return;
          setTooltip({ target: step.target, text: step.text, side: step.side || 'right' });
        } else {
          setTooltip({ floating: true, text: step.text });
        }
        await sleep(step.ms || 2200);
        if (isStale(version)) return;
        setTooltip(null);
        break;
      case 'highlight':
        await waitForRef(step.target, version);
        if (isStale(version)) return;
        setHighlights(h => ({ ...h, [step.target]: 'pulse' }));
        await sleep(step.ms || 1200);
        if (isStale(version)) return;
        setHighlights(h => { const n = { ...h }; delete n[step.target]; return n; });
        break;
      case 'wait':
        await sleep(step.ms || 800); break;
      case 'wait_user':
        await awaitUserAction(step.action, step.hint);
        break;
      case 'reset_chat':
        setConversation([]); setText(''); setAttachedFiles([]); await sleep(200); break;
      case 'artifact':
        setConversation(prev => [...prev, { role: 'artifact', title: step.title, html: step.html, kind: step.kind || 'preview', icon: step.icon || '📄' }]);
        await sleep(step.ms || 600);
        break;
      case 'attach_file':
        setAttachedFiles(prev => [...prev, { name: step.name, kind: step.kind || 'image', html: step.html }]);
        await sleep(step.ms || 400);
        break;
      case 'clear_attachments':
        setAttachedFiles([]); await sleep(120); break;
      case 'cursor_hide':
        setCursor(c => ({ ...c, visible: false })); await sleep(120); break;
      case 'final':
        setDone(true); break;
      default:
        await sleep(60);
    }
  };

  const runScenario = async () => {
    versionRef.current += 1;
    const v = versionRef.current;
    setPlaying(true);
    setHasRun(true);
    setStepIdx(0);
    const steps = scenario.steps || [];
    for (let i = 0; i < steps.length; i++) {
      if (isStale(v)) return;
      setStepIdx(i);
      await runStep(steps[i], v);
    }
    setPlaying(false);
  };

  const handleRestart = () => {
    versionRef.current += 1;
    if (streamTimer.current) clearInterval(streamTimer.current);
    setText('');
    setConversation([]);
    setDone(false);
    setCursor({ x: -200, y: -200, visible: false, clicking: false });
    setTooltip(null);
    setHighlights({});
    setModelOpen(false);
    setSelectedModel(scenario.startModel || 'Sonnet 4.6');
    setStepIdx(0);
    setPlaying(false);
    setWaitingFor(null);
    setAttachedFiles([]);
    userResolveRef.current = null;
    setHasRun(false);
  };

  // Auto-start engine on mount + restart, when mode is auto/mixed
  // (No versionRef bump in cleanup — that races with setHasRun and kills the engine)
  useEffect(() => {
    if ((mode === 'auto' || mode === 'mixed') && !hasRun) {
      const t = setTimeout(() => runScenario(), 200);
      return () => clearTimeout(t);
    }
    // eslint-disable-next-line
  }, [hasRun, mode]);

  // Component unmount-only cleanup
  useEffect(() => {
    return () => {
      versionRef.current += 1;
      if (streamTimer.current) clearInterval(streamTimer.current);
    };
  }, []);

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

  // Auto-grow textarea on content change (mimics real claude.ai input box)
  useEffect(() => {
    const ta = inputRef.current;
    if (!ta) return;
    ta.style.height = 'auto';
    const scrollH = ta.scrollHeight;
    ta.style.height = Math.min(Math.max(scrollH, 40), 260) + 'px';
  }, [text]);

  // ===== User input handlers (interactive mode + wait_user) =====
  // Once we're "waiting for user", the engine paused — user is in control.
  const userHasControl = !playing || !!waitingFor;

  const handleSendClick = () => {
    if (!userHasControl) return;
    const trimmed = text.trim();
    if (trimmed.length < 1) return;
    if (waitingFor && waitingFor.action === 'click_send') {
      // User completed the awaited action; trigger the send AND advance the engine
      const v = versionRef.current;
      sendMessage(undefined, v);
      reportUserAction('click_send');
      return;
    }
    const v = versionRef.current;
    sendMessage(undefined, v);
  };

  const handleKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendClick();
    }
  };

  const handleInputFocus = () => {
    if (waitingFor && waitingFor.action === 'focus_input') reportUserAction('focus_input');
  };

  const handlePaste = () => {
    if (!userHasControl) return;
    setText(suggestedPrompt);
    setTimeout(() => inputRef.current && inputRef.current.focus(), 30);
    if (waitingFor && waitingFor.action === 'click_paste') reportUserAction('click_paste');
  };

  const showChat = conversation.length > 0;
  const isAuto = mode === 'auto' || mode === 'mixed';

  // Tooltip positioning relative to wrapper
  const tooltipStyle = (() => {
    if (!tooltip || tooltip.floating) return null;
    const el = refsObj[tooltip.target];
    const wrap = wrapperRef.current;
    if (!el || !wrap) return null;
    const er = el.getBoundingClientRect();
    const wr = wrap.getBoundingClientRect();
    const side = tooltip.side || 'right';
    if (side === 'right')  return { left: er.right - wr.left + 14, top: er.top - wr.top + er.height / 2, transform: 'translate(0, -50%)' };
    if (side === 'left')   return { left: er.left  - wr.left - 14, top: er.top - wr.top + er.height / 2, transform: 'translate(-100%, -50%)' };
    if (side === 'top')    return { left: er.left  - wr.left + er.width / 2, top: er.top - wr.top - 14, transform: 'translate(-50%, -100%)' };
    if (side === 'bottom') return { left: er.left  - wr.left + er.width / 2, top: er.bottom - wr.top + 14, transform: 'translate(-50%, 0)' };
    return null;
  })();

  const tc = (name) => {
    const h = highlights[name];
    if (h === 'pulse') return ' claude-sim__halo';
    if (h === 'click') return ' claude-sim__clicked';
    return '';
  };

  return (
    <div className="claude-sim" ref={wrapperRef}>
      {/* Sahte tarayıcı çubuğu */}
      <div className="claude-sim__chrome">
        <div className="claude-sim__chrome-dots">
          <span style={{ background: '#FF5F57' }} />
          <span style={{ background: '#FEBC2E' }} />
          <span style={{ background: '#28C840' }} />
        </div>
        <div className="claude-sim__addr">
          <SimIcon name="lock" size={11} />
          <span style={{ marginLeft: 6 }}>claude.ai/new</span>
        </div>
        <div className="claude-sim__demo-badge">{STR.demo}</div>
      </div>

      {/* Uygulama gövdesi */}
      <div className="claude-sim__body">
        <aside className="claude-sim__sidebar">
          <div className="claude-sim__brand-row">
            <div className="claude-sim__brand">Claude</div>
            <button className="claude-sim__icon-btn" aria-label="toggle sidebar"><SimIcon name="sidebar" size={16} /></button>
          </div>
          <button ref={setRef('newChat')} className={"claude-sim__nav claude-sim__nav--primary" + tc('newChat')}>
            <span className="claude-sim__nav-icon"><SimIcon name="plus" size={15} /></span> {STR.newChat}
          </button>
          <button ref={setRef('search')} className={"claude-sim__nav" + tc('search')}><span className="claude-sim__nav-icon"><SimIcon name="search" size={15} /></span> {STR.search}</button>
          <button ref={setRef('chats')} className={"claude-sim__nav" + tc('chats')}><span className="claude-sim__nav-icon"><SimIcon name="chats" size={15} /></span> {STR.chats}</button>
          <button ref={setRef('projects')} className={"claude-sim__nav" + tc('projects')}><span className="claude-sim__nav-icon"><SimIcon name="projects" size={15} /></span> {STR.projects}</button>
          <button ref={setRef('code')} className={"claude-sim__nav" + tc('code')}><span className="claude-sim__nav-icon"><SimIcon name="code" size={15} /></span> {STR.code}</button>
          <button ref={setRef('customize')} className={"claude-sim__nav" + tc('customize')}><span className="claude-sim__nav-icon"><SimIcon name="customize" size={15} /></span> {STR.customize}</button>
          <button ref={setRef('design')} className={"claude-sim__nav" + tc('design')}><span className="claude-sim__nav-icon"><SimIcon name="design" size={15} /></span> {STR.design}</button>

          <div className="claude-sim__sidebar-section">{STR.starred}</div>
          <div className="claude-sim__sidebar-item"><SimIcon name="pin" size={11} /> 4-A Veli Bülteni</div>
          <div className="claude-sim__sidebar-item"><SimIcon name="pin" size={11} /> Kesir Sorularım</div>

          <div className="claude-sim__sidebar-section">{STR.recents}</div>
          <div className="claude-sim__sidebar-item">Ders planı taslağı</div>
          <div className="claude-sim__sidebar-item">Veli mesajı önerileri</div>

          <div className="claude-sim__profile" ref={setRef('profile')}>
            <div className="claude-sim__profile-av">{STR.youInitials}</div>
            <div>
              <div style={{ fontSize: 12, fontWeight: 600 }}>{STR.you}</div>
              <div style={{ fontSize: 10, opacity: 0.6 }}>Pro plan · DEMO</div>
            </div>
          </div>
        </aside>

        <main className="claude-sim__main">
          {!showChat && (
            <div className="claude-sim__welcome">
              <h2 className="claude-sim__greeting">
                <span className="claude-sim__star"><ClaudeMark size={26} color="#D97757" /></span>{' '}
                {scenario.greeting || (isEn ? 'How can I help you today?' : 'Bugün size nasıl yardımcı olabilirim?')}
              </h2>

              <div ref={setRef('input')} className={"claude-sim__inputbox" + tc('input') + (waitingFor && waitingFor.action === 'focus_input' ? ' claude-sim__inputbox--pulse' : '')}>
                {attachedFiles.length > 0 && (
                  <div className="claude-sim__attach-row">
                    {attachedFiles.map((a, i) => (
                      <div key={i} className="claude-sim__attach-chip">
                        <span className="claude-sim__attach-icon">{a.kind === 'image' ? '🖼️' : a.kind === 'pdf' ? '📕' : '📎'}</span>
                        <span className="claude-sim__attach-name">{a.name}</span>
                        <button className="claude-sim__attach-remove" onClick={() => setAttachedFiles(prev => prev.filter((_, j) => j !== i))} aria-label="remove">×</button>
                      </div>
                    ))}
                  </div>
                )}
                <textarea
                  ref={inputRef}
                  value={text}
                  onChange={e => setText(e.target.value)}
                  onFocus={handleInputFocus}
                  onKeyDown={handleKey}
                  rows={2}
                  placeholder={STR.placeholder}
                  className="claude-sim__textarea"
                  readOnly={isAuto && playing && !waitingFor}
                />
                <div className="claude-sim__inputbar">
                  <button ref={setRef('attach')} className={"claude-sim__plus" + tc('attach')} aria-label="attach"><SimIcon name="plus" size={14} /></button>
                  <div style={{ flex: 1 }} />
                  <div ref={setRef('modelSelector')} className={"claude-sim__model-wrap" + tc('modelSelector')}>
                    <button className="claude-sim__model" onClick={() => (!playing || waitingFor) && setModelOpen(o => !o)}>
                      {selectedModel} <SimIcon name="chevDown" size={11} />
                    </button>
                    {modelOpen && (
                      <div className="claude-sim__model-dropdown">
                        <button ref={setRef('model_opus')} className={"claude-sim__model-item" + tc('model_opus')} onClick={() => { setSelectedModel('Opus 4.7'); setModelOpen(false); }}>
                          <strong>Opus 4.7</strong>
                          <span>{isEn ? 'Most capable, best for complex thinking' : 'En güçlü, karmaşık düşünme için'}</span>
                        </button>
                        <button ref={setRef('model_sonnet')} className={"claude-sim__model-item" + tc('model_sonnet')} onClick={() => { setSelectedModel('Sonnet 4.6'); setModelOpen(false); }}>
                          <strong>Sonnet 4.6</strong>
                          <span>{isEn ? 'Balanced — most everyday tasks' : 'Dengeli — günlük işlerin çoğu'}</span>
                        </button>
                        <button ref={setRef('model_haiku')} className={"claude-sim__model-item" + tc('model_haiku')} onClick={() => { setSelectedModel('Haiku 4.5'); setModelOpen(false); }}>
                          <strong>Haiku 4.5</strong>
                          <span>{isEn ? 'Fast & cheap — simple, repetitive work' : 'Hızlı & ucuz — basit, tekrarlı iş'}</span>
                        </button>
                      </div>
                    )}
                  </div>
                  <button
                    ref={setRef('send')}
                    className={"claude-sim__send" + tc('send')}
                    onClick={handleSendClick}
                    disabled={text.trim().length < 1}
                    aria-label="send"
                  ><SimIcon name="arrowUp" size={14} /></button>
                </div>
              </div>

              <div className="claude-sim__quick">
                <button ref={setRef('chip_write')} className={"claude-sim__chip" + tc('chip_write')}><SimIcon name="pencil" size={13} /> {STR.write}</button>
                <button ref={setRef('chip_learn')} className={"claude-sim__chip" + tc('chip_learn')}><SimIcon name="grad" size={13} /> {STR.learn}</button>
                <button ref={setRef('chip_code')} className={"claude-sim__chip" + tc('chip_code')}><SimIcon name="code" size={13} /> {STR.codeBtn}</button>
                <button ref={setRef('chip_life')} className={"claude-sim__chip" + tc('chip_life')}><SimIcon name="coffee" size={13} /> {STR.lifeStuff}</button>
                <button ref={setRef('chip_drive')} className={"claude-sim__chip" + tc('chip_drive')}><SimIcon name="drive" size={13} /> {STR.fromDrive}</button>
              </div>

              {scenario.suggestedPrompt !== false && scenario.hideSuggested !== true && (
                <div className="claude-sim__suggested">
                  <div className="claude-sim__suggested-label">{STR.suggested}</div>
                  <div className="claude-sim__suggested-text">{suggestedPrompt}</div>
                  <button ref={setRef('paste')} className={"claude-sim__paste" + tc('paste')} onClick={handlePaste}>{STR.paste} <SimIcon name="arrowDown" size={12} /></button>
                </div>
              )}
            </div>
          )}

          {showChat && (
            <div ref={scrollRef} className="claude-sim__chat">
              {conversation.map((msg, i) => {
                if (msg.role === 'artifact') {
                  return (
                    <div key={i} className="claude-sim__artifact-card">
                      <div className="claude-sim__artifact-header">
                        <span className="claude-sim__artifact-icon">{msg.icon || '📄'}</span>
                        <strong className="claude-sim__artifact-title">{msg.title}</strong>
                        <div className="claude-sim__artifact-tabs">
                          <span className="claude-sim__artifact-tab claude-sim__artifact-tab--active">{isEn ? 'Preview' : 'Önizleme'}</span>
                          <span className="claude-sim__artifact-tab">{isEn ? 'Code' : 'Kod'}</span>
                        </div>
                        <div className="claude-sim__artifact-actions">
                          <button className="claude-sim__artifact-btn" aria-label="copy"><SimIcon name="code" size={12} /></button>
                          <button className="claude-sim__artifact-btn" aria-label="download"><SimIcon name="arrowDown" size={12} /></button>
                        </div>
                      </div>
                      <div className="claude-sim__artifact-body" dangerouslySetInnerHTML={{ __html: msg.html }} />
                    </div>
                  );
                }
                return (
                <div key={i} className={`claude-sim__msg claude-sim__msg--${msg.role}`}>
                  {msg.role === 'assistant' && <div className="claude-sim__avatar"><ClaudeMark size={18} color="#1F1B16" /></div>}
                  <div className="claude-sim__bubble">
                    {msg.attachments && msg.attachments.length > 0 && (
                      <div className="claude-sim__bubble-attachments">
                        {msg.attachments.map((a, j) => (
                          <div key={j} className="claude-sim__bubble-attachment" dangerouslySetInnerHTML={{ __html: a.html }} />
                        ))}
                      </div>
                    )}
                    {msg.role === 'assistant' && msg.streaming && msg.content.length === 0 ? (
                      <span className="claude-sim__typing">
                        <span className="claude-sim__dot" /><span className="claude-sim__dot" /><span className="claude-sim__dot" />
                        <span style={{ marginLeft: 8, fontSize: 12, opacity: 0.7 }}>{STR.typing}…</span>
                      </span>
                    ) : (
                      <span style={{ whiteSpace: 'pre-wrap' }}>{msg.content}{msg.streaming ? <span className="claude-sim__caret">▍</span> : null}</span>
                    )}
                  </div>
                  {msg.role === 'user' && <div className="claude-sim__avatar claude-sim__avatar--user">{STR.youInitials}</div>}
                </div>
                );
              })}

              {done && (
                <div className="claude-sim__final">
                  <div style={{ fontSize: 28, marginBottom: 6 }}>🎉</div>
                  <strong style={{ fontSize: 15 }}>{scenario.finalTitle || STR.finalTitle}</strong>
                  <p style={{ fontSize: 13, opacity: 0.85, margin: '8px 0 14px', lineHeight: 1.5 }}>{scenario.finalBody || STR.finalBody}</p>
                  <div className="row" style={{ gap: 8, justifyContent: 'center' }}>
                    <a className="claude-sim__final-btn claude-sim__final-btn--primary" href="https://claude.ai/new" target="_blank" rel="noopener noreferrer">{STR.openClaude} ↗</a>
                    <button className="claude-sim__final-btn" onClick={handleRestart}>{STR.restart}</button>
                  </div>
                </div>
              )}
            </div>
          )}

        </main>
      </div>

      {/* Sahte fare imleci — wrapper'a göre konumlanır (sidebar dahil) */}
      {cursor.visible && (
        <div
          className={"claude-sim__cursor" + (cursor.clicking ? ' claude-sim__cursor--clicking' : '')}
          style={{ transform: `translate(${cursor.x}px, ${cursor.y}px)` }}
          aria-hidden="true"
        >
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
            <path d="M3 2 L3 17 L7 13 L10 19 L12 18 L9 12 L15 12 Z" fill="#fff" stroke="#1F1B16" strokeWidth="1.3" strokeLinejoin="round"/>
          </svg>
        </div>
      )}

      {/* Tooltip katmanı — yine wrapper-relative */}
      {tooltip && tooltip.floating && (
        <div className="claude-sim__tooltip claude-sim__tooltip--floating">
          {tooltip.text}
        </div>
      )}
      {tooltip && !tooltip.floating && tooltipStyle && (
        <div className={`claude-sim__tooltip claude-sim__tooltip--${tooltip.side || 'right'}`} style={tooltipStyle}>
          {tooltip.text}
        </div>
      )}

      {/* Senaryo / kontrol çubuğu */}
      <div className="claude-sim__playbar" style={{ borderTopColor: color }}>
        <div className="claude-sim__playbar-status">
          {waitingFor ? (
            <><span className="claude-sim__playbar-badge claude-sim__playbar-badge--user" style={{ background: color }}>{isEn ? 'Your turn' : 'Sıra sende'}</span> {waitingFor.hint}</>
          ) : playing ? (
            <><span className="claude-sim__playbar-badge" style={{ background: color }}>{isEn ? 'Playing' : 'Oynuyor'} {scenario.steps ? `${stepIdx + 1}/${scenario.steps.length}` : ''}</span> {scenario.intro || (isEn ? 'Watch the demo…' : 'Demoyu izleyin…')}</>
          ) : !hasRun && isAuto ? (
            <><span className="claude-sim__playbar-badge" style={{ background: color }}>{isEn ? 'Demo' : 'Demo'}</span> {scenario.intro || (isEn ? 'Click play to watch the walkthrough.' : 'Adım adım izlemek için Başlat\'a basın.')}</>
          ) : done ? (
            <><span className="claude-sim__playbar-badge" style={{ background: '#4F9D52' }}>{isEn ? 'Done' : 'Bitti'}</span> {isEn ? 'Try it yourself or replay.' : 'Kendin dene ya da tekrar izle.'}</>
          ) : (
            <><span className="claude-sim__playbar-badge" style={{ background: color }}>{isEn ? 'Try it' : 'Sen dene'}</span> {scenario.intro || (isEn ? 'Type a prompt and press Enter.' : 'Bir prompt yazıp Enter\'a bas.')}</>
          )}
        </div>
        <div className="claude-sim__playbar-actions">
          {isAuto && !waitingFor && (
            <button className="claude-sim__playbar-btn" onClick={handleRestart} disabled={playing && !hasRun}>
              {!hasRun ? (isEn ? '▶ Start' : '▶ Başlat') : playing ? (isEn ? '↻ Restart' : '↻ Yeniden') : (isEn ? '↻ Replay' : '↻ Tekrar')}
            </button>
          )}
          {!isAuto && (conversation.length > 0 || done) && (
            <button className="claude-sim__playbar-btn" onClick={handleRestart}>{isEn ? '↻ Reset' : '↻ Sıfırla'}</button>
          )}
        </div>
      </div>
    </div>
  );
}

window.ModulePage = ModulePage;
window.PromptBlock = PromptBlock;
window.MermaidBlock = MermaidBlock;
window.ActivityContent = ActivityContent;
window.ClaudeSimulator = ClaudeSimulator;
