// Araç Kütüphanesi + Profil/İlerleme + Sertifika
function ToolsPage() {
  const data = window.APP_DATA;
  const [filter, setFilter] = useState('all');
  const t = window.t;
  const categories = ['all', ...new Set(data.tools.map(tool => tool.category))];
  const filtered = filter === 'all' ? data.tools : data.tools.filter(tool => tool.category === filter);

  return (
    <div className="page fade-up">
      <div className="page-header">
        <div className="kicker">{t('tools.kicker')}</div>
        <h1 className="page-title">{t('tools.title_1')}<br/>{t('tools.title_2')}</h1>
        <p className="page-sub">{t('tools.lede')}</p>
      </div>

      {/* Filter chips */}
      <div className="row" style={{ gap: 8, marginBottom: 28, flexWrap: 'wrap' }}>
        {categories.map(c => (
          <button
            key={c}
            onClick={() => setFilter(c)}
            className="btn btn-sm"
            style={{
              background: filter === c ? 'var(--ink)' : 'transparent',
              color: filter === c ? 'var(--bg)' : 'var(--ink-2)',
              border: filter === c ? '1.5px solid var(--ink)' : '1.5px solid var(--line)',
            }}
          >
            {c === 'all' ? t('tools.all_categories') : c}
          </button>
        ))}
      </div>

      {/* Tool grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
        {filtered.map(tool => (
          <div key={tool.name} className="card" style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <div className="row" style={{ gap: 12, alignItems: 'flex-start' }}>
              <div style={{
                width: 44, height: 44, borderRadius: 12,
                background: `var(--${tool.color})`,
                display: 'grid', placeItems: 'center',
                color: '#fff', fontWeight: 700, fontSize: 18,
                fontFamily: 'var(--font-display)',
                flexShrink: 0,
              }}>{tool.name[0]}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 16, lineHeight: 1.1 }}>{tool.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{tool.vendor}</div>
              </div>
              <span className={`chip chip-${tool.color}`} style={{ fontSize: 10 }}>{tool.category}</span>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontSize: 12, marginTop: 4 }}>
              <div style={{ padding: '8px 10px', background: 'var(--bg-soft)', borderRadius: 8 }}>
                <div style={{ color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.1em', fontWeight: 600, marginBottom: 2 }}>{t('tools.free_caps')}</div>
                <div style={{ fontWeight: 600 }}>{tool.free}</div>
              </div>
              <div style={{ padding: '8px 10px', background: 'var(--bg-soft)', borderRadius: 8 }}>
                <div style={{ color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.1em', fontWeight: 600, marginBottom: 2 }}>{t('tools.paid_caps')}</div>
                <div style={{ fontWeight: 600 }}>{tool.paid}</div>
              </div>
            </div>

            <div style={{ marginTop: 4 }}>
              <div style={{ color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.1em', fontWeight: 600, marginBottom: 6 }}>{t('tools.best_caps')}</div>
              <p style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.4 }}>{tool.best}</p>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginTop: 4 }}>
              {tool.strengths.map((s, i) => (
                <div key={i} className="row" style={{ gap: 6, fontSize: 12.5, color: 'var(--ink-2)' }}>
                  <span style={{ color: `var(--${tool.color})`, fontSize: 9 }}>●</span>
                  {s}
                </div>
              ))}
            </div>

            <div style={{ marginTop: 'auto', paddingTop: 10, borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <code style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>{tool.url}</code>
              <a
                href={tool.url.startsWith('http') ? tool.url : `https://${tool.url}`}
                target="_blank"
                rel="noopener noreferrer"
                className="btn btn-ghost btn-sm"
                style={{ padding: '4px 10px', fontSize: 11, textDecoration: 'none' }}
              >{t('tools.open')} ↗</a>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ProfilePage({ setPage, setModule }) {
  const data = window.APP_DATA;
  const { user, modules } = data;
  const pct = Math.round((user.completed.length / modules.length) * 100);
  const t = window.t;
  const isEn = window.LANG === 'en';

  const badges = [
    { name: t('badge.first_step_name'), desc: t('badge.first_step_desc'), emoji: '🌱', earned: user.completed.includes(0), color: 'moss' },
    { name: t('badge.chatter_name'), desc: t('badge.chatter_desc'), emoji: '💬', earned: user.completed.includes(1), color: 'sun' },
    { name: t('badge.prompt_master_name'), desc: t('badge.prompt_master_desc'), emoji: '✍️', earned: user.completed.includes(2), color: 'coral' },
    { name: t('badge.artifact_name'), desc: t('badge.artifact_desc'), emoji: '🎨', earned: user.completed.includes(4), color: 'sky' },
    { name: t('badge.excel_name'), desc: t('badge.excel_desc'), emoji: '📊', earned: user.completed.includes(7), color: 'moss' },
    { name: t('badge.cert_name'), desc: t('badge.cert_desc'), emoji: '🏆', earned: user.completed.length === modules.length, color: 'rose' },
  ];
  const earnedCount = badges.filter(b => b.earned).length;

  return (
    <div className="page fade-up">
      {/* Profile header */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr auto', gap: 32, alignItems: 'center',
        marginBottom: 40,
      }}>
        <div className="row" style={{ gap: 20 }}>
          <div style={{
            width: 88, height: 88, borderRadius: 24,
            background: 'linear-gradient(135deg, var(--lavender), var(--rose))',
            display: 'grid', placeItems: 'center', color: '#fff', fontWeight: 700, fontSize: 34,
            fontFamily: 'var(--font-display)',
            boxShadow: 'var(--shadow-md)',
          }}>{user.initials}</div>
          <div>
            <div className="kicker" style={{ marginBottom: 6 }}>{t('profile.kicker')}</div>
            <h1 style={{ fontSize: 36, letterSpacing: '-0.02em', marginBottom: 4 }}>{user.name}</h1>
            <p style={{ color: 'var(--ink-2)', fontSize: 15 }}>{user.role}{user.school ? ` · ${user.school}` : ''}</p>
          </div>
        </div>
        <div className="row" style={{ gap: 8 }}>
          <button className="btn btn-ghost btn-sm"><Icon name="settings" size={14} /> {t('profile.settings')}</button>
        </div>
      </div>

      {/* Stats strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 40 }}>
        {[
          { num: `${user.completed.length}`, label: t('profile.stat_done'), sub: `${modules.length - user.completed.length} ${t('profile.stat_remaining_1')}`, color: 'moss', emoji: '📚' },
          { num: isEn ? `${pct}%` : `%${pct}`, label: t('profile.stat_progress'), sub: pct === 100 ? t('profile.stat_progress_done') : t('profile.stat_progress_going'), color: 'lavender', emoji: '📊' },
          { num: `${user.streak}`, label: t('profile.stat_streak'), sub: user.streak > 0 ? t('profile.stat_streak_active') : t('profile.stat_streak_inactive'), color: 'coral', emoji: '🔥' },
          { num: `${earnedCount}`, label: t('profile.stat_badges'), sub: `${badges.length - earnedCount} ${t('profile.stat_badges_more')}`, color: 'sun', emoji: '⭐' },
        ].map((s, i) => (
          <div key={i} className="card" style={{ padding: 22, position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', top: -10, right: -10, fontSize: 70, opacity: 0.12, transform: 'rotate(-12deg)' }}>{s.emoji}</div>
            <div className="kicker" style={{ color: `var(--${s.color === 'lavender' ? 'lavender' : s.color})`, fontWeight: 700, marginBottom: 10 }}>{s.label.toUpperCase()}</div>
            <div style={{ fontSize: 40, fontFamily: 'var(--font-display)', fontWeight: 700, lineHeight: 1, letterSpacing: '-0.03em' }}>{s.num}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>{s.sub}</div>
          </div>
        ))}
      </div>

      {/* Two-column: badges + roadmap */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 32 }}>
        {/* Badges */}
        <div>
          <div className="kicker" style={{ marginBottom: 8 }}>{t('profile.badges_kicker')} · {earnedCount}/{badges.length}</div>
          <h2 className="section-title" style={{ marginBottom: 20 }}>{t('profile.badges_title')}</h2>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
            {badges.map(b => (
              <div key={b.name} className="card" style={{
                padding: 18,
                textAlign: 'center',
                opacity: b.earned ? 1 : 0.45,
                filter: b.earned ? 'none' : 'grayscale(0.4)',
                background: b.earned ? `linear-gradient(135deg, var(--${b.color}-soft), var(--bg-elevated))` : 'var(--bg-elevated)',
                border: `1.5px solid var(--${b.color})30`,
              }}>
                <div style={{ fontSize: 44, marginBottom: 8, filter: b.earned ? 'drop-shadow(0 4px 6px rgba(0,0,0,0.15))' : 'none' }}>{b.emoji}</div>
                <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 4 }}>{b.name}</div>
                <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{b.desc}</div>
                {!b.earned && <div className="chip" style={{ marginTop: 8, fontSize: 9, padding: '2px 8px' }}>{t('profile.locked')}</div>}
              </div>
            ))}
          </div>
        </div>

        {/* Certificate teaser */}
        <div>
          <div className="kicker" style={{ marginBottom: 8 }}>{t('profile.goal_kicker')}</div>
          <h2 className="section-title" style={{ marginBottom: 20 }}>{t('profile.goal_title')}</h2>
          <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
            {/* Certificate preview */}
            <div style={{
              aspectRatio: '4/3',
              background: `
                linear-gradient(135deg, var(--sun-soft), var(--coral-soft), var(--lavender-soft)),
                var(--bg-soft)
              `,
              padding: 28,
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'center',
              alignItems: 'center',
              textAlign: 'center',
              gap: 8,
              position: 'relative',
              filter: 'saturate(0.8)',
            }}>
              <div style={{ position: 'absolute', inset: 16, border: '2px dashed rgba(31,27,22,0.15)', borderRadius: 12 }} />
              <div style={{ fontSize: 48 }}>🏆</div>
              <div className="kicker">{t('profile.cert_kicker')}</div>
              <div style={{ fontSize: 22, fontFamily: 'var(--font-display)', letterSpacing: '-0.02em', fontWeight: 700, lineHeight: 1.1 }}>
                {t('profile.cert_title')}<br/>{t('profile.cert_subtitle')}
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 4 }}>{user.name}</div>
              <div style={{ fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', marginTop: 2 }}>{t('profile.cert_modules_caps')}</div>
            </div>
            <div style={{ padding: 18 }}>
              <div className="row" style={{ justifyContent: 'space-between', marginBottom: 10 }}>
                <span style={{ fontSize: 13, fontWeight: 600 }}>{t('profile.completion_rate')}</span>
                <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--moss-deep)' }}>{isEn ? `${pct}%` : `%${pct}`}</span>
              </div>
              <div style={{ height: 8, background: 'var(--bg-soft)', borderRadius: 4, overflow: 'hidden', marginBottom: 12 }}>
                <div style={{ height: '100%', width: pct + '%', background: `linear-gradient(90deg, var(--moss), var(--sun), var(--coral))`, borderRadius: 4 }} />
              </div>
              <p style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.5, marginBottom: 14 }}>
                {t('profile.cert_body_1')} <strong>{modules.length - user.completed.length} {isEn ? 'modules' : 'modülü'}</strong> {t('profile.cert_body_2')}
              </p>
              <button className="btn btn-primary btn-sm" onClick={() => setPage('path')} style={{ width: '100%', justifyContent: 'center' }}>
                {t('profile.go_next_module')} <Icon name="arrow" size={13} />
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Kazanılan sertifikalar */}
      <CertificatesList modules={modules} />

      {/* Activity timeline */}
      <ActivityTimeline modules={modules} />
    </div>
  );
}

function CertificatesList({ modules }) {
  const t = window.t;
  const isEn = window.LANG === 'en';
  const [certs, setCerts] = useState(null);

  useEffect(() => {
    fetch('api/certificates/mine', { credentials: 'same-origin' })
      .then(r => r.json())
      .then(d => setCerts(d.items || []))
      .catch(() => setCerts([]));
  }, []);

  if (certs === null) return null;

  return (
    <div style={{ marginTop: 48 }}>
      <div className="kicker" style={{ marginBottom: 8 }}>{t('cert.my_certs').toUpperCase()}</div>
      <h2 className="section-title" style={{ marginBottom: 20 }}>{t('cert.my_certs')}</h2>
      {certs.length === 0 ? (
        <div className="card" style={{ padding: 24, color: 'var(--ink-3)', fontSize: 13 }}>
          {t('cert.my_certs_empty')}
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
          {certs.map(c => {
            const mod = modules.find(m => m.id === c.module_id) || { title: '?', color: 'moss' };
            const certUrl = `${location.origin}/sertifika/${c.id}`;
            const svgUrl = `${location.origin}/sertifika/${c.id}.svg?lang=${isEn ? 'en' : 'tr'}`;
            const earnedDate = new Date(c.earned_at).toLocaleDateString(isEn ? 'en-US' : 'tr-TR', { day: '2-digit', month: 'short', year: 'numeric' });
            return (
              <div key={c.id} className="card" style={{ padding: 0, overflow: 'hidden' }}>
                <a href={certUrl} target="_blank" rel="noopener noreferrer" style={{ display: 'block', borderBottom: '1px solid var(--line)' }}>
                  <img
                    src={svgUrl}
                    alt={mod.title}
                    style={{ width: '100%', height: 'auto', display: 'block', background: 'var(--bg-soft)' }}
                  />
                </a>
                <div style={{ padding: 14 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>{mod.title}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>
                    {t('cert.earned_on')}: {earnedDate} · #{c.id}
                  </div>
                  <div className="row" style={{ gap: 8, marginTop: 10 }}>
                    <a href={certUrl} target="_blank" rel="noopener noreferrer" className="btn btn-primary btn-sm" style={{ flex: 1, justifyContent: 'center' }}>
                      {t('cert.view')}
                    </a>
                    <a href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(certUrl)}`} target="_blank" rel="noopener noreferrer" className="btn btn-ghost btn-sm" style={{ flex: 1, justifyContent: 'center' }}>
                      {t('cert.share')}
                    </a>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

function formatRelative(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  const now = new Date();
  const diff = (now - d) / 1000;
  const sameDay = d.toDateString() === now.toDateString();
  const yesterday = new Date(now); yesterday.setDate(now.getDate() - 1);
  const isYesterday = d.toDateString() === yesterday.toDateString();
  const hhmm = d.toTimeString().slice(0, 5);
  const t = window.t;
  const locale = window.LANG === 'en' ? 'en-US' : 'tr-TR';
  if (diff < 60) return t('time.just_now');
  if (sameDay) return `${t('time.today')} · ${hhmm}`;
  if (isYesterday) return `${t('time.yesterday')} · ${hhmm}`;
  if (diff < 86400 * 7) return `${Math.floor(diff / 86400)} ${t('time.days_ago')}`;
  if (diff < 86400 * 30) return `${Math.floor(diff / 86400 / 7)} ${t('time.weeks_ago')}`;
  return d.toLocaleDateString(locale, { day: '2-digit', month: 'long', year: 'numeric' });
}

function ActivityTimeline({ modules }) {
  const [activity, setActivity] = useState(null);
  const t = window.t;

  useEffect(() => {
    window.API.getActivity().then(setActivity).catch(err => {
      console.warn('[activity]', err.message);
      setActivity({ joined_at: null, completions: [] });
    });
  }, []);

  if (!activity) {
    return (
      <div style={{ marginTop: 48 }}>
        <div className="kicker" style={{ marginBottom: 8 }}>{t('profile.activity_kicker')}</div>
        <h2 className="section-title" style={{ marginBottom: 20 }}>{t('profile.activity_title')}</h2>
        <div className="card" style={{ padding: 24, color: 'var(--ink-3)', fontSize: 13 }}>{t('profile.activity_loading')}</div>
      </div>
    );
  }

  const events = [
    ...activity.completions.map(c => {
      const mod = modules.find(m => m.id === c.module_id);
      return {
        time: c.completed_at,
        emoji: '✅',
        color: mod ? mod.color : 'moss',
        title: mod ? mod.title : `${t('common.module')} ${c.module_id + 1}`,
        detail: t('profile.activity_module_done'),
      };
    }),
    ...(activity.joined_at ? [{
      time: activity.joined_at,
      emoji: '🎉',
      color: 'sun',
      title: t('profile.activity_welcome'),
      detail: t('profile.activity_joined'),
    }] : []),
  ];

  return (
    <div style={{ marginTop: 48 }}>
      <div className="kicker" style={{ marginBottom: 8 }}>{t('profile.activity_kicker')}</div>
      <h2 className="section-title" style={{ marginBottom: 20 }}>{t('profile.activity_title')}</h2>
      <div className="card" style={{ padding: 24 }}>
        {events.length === 0 ? (
          <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>{t('profile.activity_empty')}</div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            {events.map((a, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '160px 32px 1fr', gap: 16, alignItems: 'center' }}>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>{formatRelative(a.time)}</div>
                <div style={{
                  width: 32, height: 32, borderRadius: 10,
                  background: `var(--${a.color}-soft)`,
                  display: 'grid', placeItems: 'center', fontSize: 16,
                }}>{a.emoji}</div>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{a.title}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{a.detail}</div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

window.ToolsPage = ToolsPage;
window.ProfilePage = ProfilePage;
