// Einführung für neue Spieler: kurze Schritt-für-Schritt-Tour mit hervorgehobenen Bereichen (Coachmarks).
import { art } from './art.js';
import { S } from './state.js';
import { esc, $, eur } from './util.js';
import { GLOSSARY } from './ui.js';
const isMobile = () => matchMedia('(max-width: 760px)').matches;
const STEPS = () => [
{ view: 'markt', sel: null, title: 'Willkommen in Wiborien!',
text: `Du startest mit ${eur(S.info?.startCash ?? 100000, 0)} Spielgeld. Ziel: dein Depot klüger wachsen lassen als die anderen – über eine Saison von mehreren Wochen. Die Einführung dauert etwa zwei Minuten.` },
{ view: 'markt', sel: () => '#phase', title: 'Die Börsenuhr',
text: 'Gehandelt wird zu festen Zeiten: Vorbörse, Eröffnungsauktion, fortlaufender Handel und Schlussauktion. Außerhalb der Handelszeit werden Orders gesammelt und in der nächsten Auktion ausgeführt – du musst also nicht ständig online sein.' },
{ view: 'markt', sel: () => '#marketCol', title: 'Der Markt',
text: 'Hier siehst du alle Aktien mit Kurs und Tagesveränderung (▲/▼). Kennzeichen wie „Auktion“, „VU“ (Volatilitätsunterbrechung), „HTB“ oder „Zahlen in 2 T“ zeigen Besonderheiten. Tippe auf eine Aktie, um sie zu öffnen.' },
{ view: 'handeln', sel: () => '#stockCol', title: 'Die Aktie',
text: 'Chart, Kennzahlen und Hintergründe. Unter „Unternehmen“ findest du Gewinne, Dividende und die Spanne der Analysten-Kursziele. Unterstrichene Begriffe wie KGV erklären sich, wenn du sie antippst.' },
{ view: 'handeln', sel: () => '#ticketCard', title: 'Eine Order aufgeben',
text: `Wähle Kaufen oder Verkaufen, die Stückzahl und den Ordertyp. Tipp für den Anfang: Eine Limit-Order legt deinen Höchstpreis fest. ${GLOSSARY.Limit.split(':')[1] ?? ''} Der Einsteiger-Modus blendet fortgeschrittene Optionen aus.` },
{ view: 'depot', sel: () => '#v-depot', title: 'Dein Depot',
text: 'Positionen, Gewinn/Verlust, offene Orders und deine Margin-Auslastung. Für die Rangliste zählen nur Spieler mit einer Mindestzahl an Trades – Nichtstun gewinnt nicht.' },
{ view: 'heute', sel: () => '#v-heute .today', title: 'Mein Tag',
text: 'Hier steht alles, was für dich ansteht: Abstimmungen, Hauptversammlungen, Tipps, Einladungen und Belohnungen – nach Dringlichkeit sortiert und mit einem Knopf, der direkt hinführt. Die Zahl „zu tun“ oben im Kopf bringt dich jederzeit hierher. Die Einsteigertipps findest du hier unter „Erste Schritte“.' },
{ view: isMobile() ? 'mehr' : 'markt', sel: () => (isMobile() ? '#v-mehr' : '#mainnav'), title: 'Mehr entdecken',
text: 'Im Parlament stimmst du über Gesetze ab, die Kurse bewegen. In Battles trittst du gegen andere an. Tägliche Aufgaben bringen Erfahrung und Ligaaufstieg. Viel Erfolg!' },
];
let idx = 0;
let box = null;
let navigate = () => {};
let finish = () => {};
function place() {
const steps = STEPS();
const st = steps[idx];
const target = st.sel ? $(st.sel()) : null;
const spot = box.querySelector('.tour-spot');
const card = box.querySelector('.tour-card');
card.innerHTML = `${idx === 0 ? `
${art('cap', { cls: 'dlg-art-i' })}
` : ''}
Schritt ${idx + 1} von ${steps.length}
${esc(st.title)}
${esc(st.text)}
${idx > 0 ? '' : ''}
`;
const has = !!target && target.offsetParent !== null;
box.classList.toggle('nospot', !has);
if (has) {
target.scrollIntoView({ block: 'nearest' });
// nicht unter der festen Kopfzeile verstecken
const hdr = $('header.top')?.getBoundingClientRect().bottom ?? 0;
const r0 = target.getBoundingClientRect();
if (r0.top < hdr + 6 && r0.height < window.innerHeight - hdr) window.scrollBy(0, r0.top - hdr - 8);
const r = target.getBoundingClientRect();
const pad = 6;
const top = Math.max(4, r.top - pad), left = Math.max(4, r.left - pad);
const h = Math.min(window.innerHeight - top - 4, r.height + pad * 2), w = Math.min(window.innerWidth - left - 4, r.width + pad * 2);
Object.assign(spot.style, { display: 'block', top: `${top}px`, left: `${left}px`, width: `${w}px`, height: `${h}px` });
const ch = card.offsetHeight, cw = card.offsetWidth;
let ct = top + h + 10;
if (ct + ch > window.innerHeight - 8) ct = Math.max(8, top - ch - 10);
if (ct + ch > window.innerHeight - 8 || ct < 8) ct = Math.max(8, window.innerHeight - ch - 8);
let cl = Math.max(8, Math.min(window.innerWidth - cw - 8, left));
// hohes Ziel: Karte daneben statt darüber legen, wenn Platz ist
if (h > window.innerHeight * 0.5) {
if (left + w + cw + 16 < window.innerWidth) { cl = left + w + 12; ct = Math.max(8, top); }
else if (left - cw - 12 > 8) { cl = left - cw - 12; ct = Math.max(8, top); }
}
Object.assign(card.style, { top: `${ct}px`, left: `${cl}px`, transform: 'none' });
} else {
spot.style.display = 'none';
Object.assign(card.style, { top: '50%', left: '50%', transform: 'translate(-50%, -50%)' });
}
card.querySelector('[data-tour="next"]').focus();
}
function go(i) {
const steps = STEPS();
if (i >= steps.length) { end(true); return; }
idx = Math.max(0, i);
navigate(steps[idx].view);
requestAnimationFrame(() => requestAnimationFrame(place));
}
function end(done) {
box?.remove();
box = null;
window.removeEventListener('resize', onResize);
finish(done);
}
const onResize = () => { if (box) place(); };
/** Tour starten. nav(view) wechselt die Ansicht, onEnd(fertig) wird am Ende aufgerufen. */
export function startTour(nav, onEnd) {
navigate = nav; finish = onEnd;
box?.remove();
box = document.createElement('div');
box.className = 'tour';
box.innerHTML = '';
document.body.append(box);
box.addEventListener('click', (e) => {
const b = e.target.closest('[data-tour]');
if (!b) return;
if (b.dataset.tour === 'next') go(idx + 1);
else if (b.dataset.tour === 'back') go(idx - 1);
else end(false);
});
box.addEventListener('keydown', (e) => {
if (e.key === 'Escape') { e.preventDefault(); end(false); }
if (e.key === 'Tab') {
const f = [...box.querySelectorAll('button')];
const i = f.indexOf(document.activeElement);
if (e.shiftKey && i <= 0) { e.preventDefault(); f[f.length - 1].focus(); }
else if (!e.shiftKey && i === f.length - 1) { e.preventDefault(); f[0].focus(); }
}
});
window.addEventListener('resize', onResize);
go(0);
}