const LANGUAGE_STORAGE_KEY = 'steplet-language';

const translations = {
  ja: {
    meta: {
      title: 'STEPLET — バーチャルスニーカーを、歩いて集める。',
      description: '毎日の一歩でバーチャルスニーカーを集める、歩いて遊ぶコレクションゲーム。',
    },
    nav: { about: 'Stepletとは', how: '遊び方', contact: 'お問い合わせ', download: 'ダウンロード' },
    store: { appStore: 'App Store でダウンロード', googlePlay: 'Google Play でダウンロード' },
    hero: {
      lead: 'バーチャルスニーカーを、歩いて集める。',
      body: '毎日の一歩が、コレクションに変わる。Stepletは歩数をゲーム内通貨に変え、お気に入りのバーチャルスニーカーを集めて飾るコレクションゲームです。',
      imageAlt: 'Steplet アプリ画面',
    },
    marquee: ['WALK TO COLLECT', 'CHECK IN', 'COMPLETE THE SET', 'CURATE YOUR SHOWCASE', 'TRADE THE MARKET', 'バーチャルスニーカー', '一歩が、価値になる。'],
    concept: {
      heading: <>歩く、それだけで<br/><span style={{color:'var(--steplet-primary)'}}>世界が変わる。</span></>,
      body: 'Stepletは、現実の歩数をバーチャルスニーカーに変える「歩いて集める」プラットフォーム。通勤、散歩、ランニング — どんな一歩でも、ゲームの中の資産になります。',
      cards: [
        { title: <>歩数が <span className="accent">ゲーム内通貨</span>に。</>, body: 'スマートフォンのモーションデータと連携して、毎日の歩数を自動で記録。歩いた分だけ、ゲーム内通貨「Steplet」が貯まります。' },
        { title: <><span className="accent">スニーカー</span>で個性を。</>, body: 'デザインも性能も異なる、何百種類ものバーチャルスニーカー。あなたの足元から、コレクターとしての個性が始まります。' },
        { title: <>ショーケースに <span className="accent">並べる</span>、マーケットで <span className="accent">交わる</span>。</>, body: '集めたスニーカーは、ショーケースに展示。ダブついたものはマーケットで売却。コレクター同士で、価値が動き出す。' },
      ],
    },
    flow: {
      heading: <>歩く → チェックイン →<br/>集める → 飾る → トレード</>,
      steps: [
        { title: '歩く。', body: '通勤も、散歩も、トレーニングも。スマートフォンのモーションデータから歩数を記録し、歩いた分だけStepletが貯まります。', chips: ['歩数を自動記録', 'バックグラウンド計測', 'GPSなしでもOK'], badge: '歩いて探索', alt: '探索マップ画面' },
        { title: 'チェックインする。', body: '街にあるスポットに到着したら、その場でチェックイン。貯めたStepletでスニーカーボックスを購入し、タップ＆フリックで開封する瞬間がたまらない。', chips: ['スポット発見', '開封演出', '限定ドロップ'], badge: 'スポットを開放', alt: 'スポットが開放された画面' },
        { title: '集める。', body: 'シリーズごとの全色を揃える、新作モデルを誰よりも早く手に入れる。1足、また1足と埋まっていく図鑑が、また歩きたくなる理由になる。コンプリート時には特別な報酬も。', chips: ['シリーズ図鑑', 'コンプリート報酬', '新作通知'], badge: 'コレクションを埋める', alt: 'コレクションを埋める画面' },
        { title: '飾る。', body: 'バーチャルショーケースに自分のコレクションを展示。壁紙、棚、床まで自由にカスタマイズして、自分だけのショーケースを完成させよう。友達と見せ合うのも楽しい。', chips: ['ショーケース編集', '壁紙カスタム', 'フレンド公開'], badge: 'ショーケースに飾る', alt: 'ショーケース画面' },
        { title: 'トレードする。', body: 'マーケットに出品して、コレクター同士でトレード。需要と希少性が価値を決める、リアルなセカンダリーマーケット。手放した一足が、誰かのお気に入りになる。', chips: ['即時出品', '価格自由設定', '売り切れバッジ'], badge: 'マーケットで取引', alt: 'マーケット画面' },
      ],
    },
    cta: {
      heading: <>さあ、<br/><span className="underline">最初の一歩</span>を。</>,
      body: 'iOSとAndroid、両方のストアで配信中。今すぐダウンロードして、あなただけのコレクションを始めよう。',
    },
    footer: {
      tagline: <>バーチャルスニーカーを集めよう。<br/>一歩、また一歩。あなたのコレクションが、世界を変える。</>,
      terms: '利用規約', privacy: 'プライバシーポリシー', feedback: 'ご意見・不具合報告', twitter: 'X(旧Twitter)',
    },
  },
  en: {
    meta: {
      title: 'STEPLET — Walk. Collect. Flex.',
      description: 'Turn every step into a virtual sneaker collection in Steplet, the collection game built for walking.',
    },
    nav: { about: 'About', how: 'How it works', contact: 'Contact', download: 'Download' },
    store: { appStore: 'Download on the App Store', googlePlay: 'Get it on Google Play' },
    hero: {
      lead: 'Walk your way to a virtual sneaker collection.',
      body: 'Every step adds to your collection. Steplet turns your steps into in-game currency so you can collect, display, and trade virtual sneakers you love.',
      imageAlt: 'Steplet app screen',
    },
    marquee: ['WALK TO COLLECT', 'CHECK IN', 'COMPLETE THE SET', 'CURATE YOUR SHOWCASE', 'TRADE THE MARKET', 'VIRTUAL SNEAKERS', 'MAKE EVERY STEP COUNT.'],
    concept: {
      heading: <>Just start walking.<br/><span style={{color:'var(--steplet-primary)'}}>Watch your world change.</span></>,
      body: 'Steplet turns real-world steps into virtual sneakers. Your commute, evening walk, or daily run — every step becomes part of the game.',
      cards: [
        { title: <>Turn steps into <span className="accent">in-game currency.</span></>, body: 'Steplet connects to your phone’s motion data and tracks your steps automatically. The farther you walk, the more Steplet currency you earn.' },
        { title: <>Show your style with <span className="accent">sneakers.</span></>, body: 'Collect hundreds of virtual sneakers, each with its own design and performance. Your collection says who you are.' },
        { title: <><span className="accent">Curate</span> your showcase. <span className="accent">Connect</span> through the market.</>, body: 'Put your favorites on display and list your duplicates on the market. Every trade keeps value moving between collectors.' },
      ],
    },
    flow: {
      heading: <>Walk → Check in → Collect →<br/>Display → Trade</>,
      steps: [
        { title: 'Walk.', body: 'Commute, stroll, or train. Steplet reads your phone’s motion data and rewards every step with in-game currency.', chips: ['Automatic tracking', 'Background tracking', 'No GPS required'], badge: 'Explore on foot', alt: 'Explore map screen' },
        { title: 'Check in.', body: 'Reach a spot in the city and check in. Spend your Steplet currency on a sneaker box, then tap and flick to reveal your next pair.', chips: ['Discover spots', 'Interactive unboxing', 'Limited drops'], badge: 'Unlock a spot', alt: 'Unlocked spot screen' },
        { title: 'Collect.', body: 'Complete every colorway in a series or be first to find a new release. Watching your catalog fill up gives every walk a new purpose — with special rewards for completed sets.', chips: ['Series catalog', 'Set rewards', 'New drop alerts'], badge: 'Build your collection', alt: 'Sneaker collection screen' },
        { title: 'Display.', body: 'Build a virtual showcase for your collection. Customize the walls, shelves, and floor, then share your space with friends.', chips: ['Showcase editor', 'Custom interiors', 'Share with friends'], badge: 'Curate your showcase', alt: 'Virtual showcase screen' },
        { title: 'Trade.', body: 'List sneakers and trade with other collectors. Demand and rarity shape a living secondary market, where a pair you release can become someone else’s favorite.', chips: ['Instant listings', 'Set your price', 'Sold badges'], badge: 'Trade on the market', alt: 'Sneaker market screen' },
      ],
    },
    cta: {
      heading: <>Take your<br/><span className="underline">first step.</span></>,
      body: 'Available now on iOS and Android. Download Steplet and start building a collection that is uniquely yours.',
    },
    footer: {
      tagline: <>Collect virtual sneakers.<br/>Step by step, build a collection that changes your world.</>,
      terms: 'Terms of Service', privacy: 'Privacy Policy', feedback: 'Feedback & bug reports', twitter: 'X (formerly Twitter)',
    },
  },
};

function detectLanguage() {
  try {
    const saved = window.localStorage.getItem(LANGUAGE_STORAGE_KEY);
    if (saved === 'ja' || saved === 'en') return saved;
  } catch (_) {
    // ストレージを利用できない環境ではブラウザ言語へフォールバックする。
  }

  const languages = navigator.languages?.length ? navigator.languages : [navigator.language];
  for (const language of languages) {
    const normalized = language?.toLowerCase();
    if (normalized?.startsWith('ja')) return 'ja';
    if (normalized?.startsWith('en')) return 'en';
  }
  return 'en';
}

const LanguageContext = React.createContext(null);

function LanguageProvider({ children }) {
  const [language, setLanguage] = React.useState(detectLanguage);

  React.useEffect(() => {
    const copy = translations[language];
    document.documentElement.lang = language;
    document.title = copy.meta.title;
    document.querySelector('meta[name="description"]')?.setAttribute('content', copy.meta.description);
    try {
      window.localStorage.setItem(LANGUAGE_STORAGE_KEY, language);
    } catch (_) {
      // 保存できなくても現在のセッションでは切り替えを継続する。
    }
  }, [language]);

  const value = React.useMemo(() => ({ language, setLanguage, copy: translations[language] }), [language]);
  return <LanguageContext.Provider value={value}>{children}</LanguageContext.Provider>;
}

function useLanguage() {
  const context = React.useContext(LanguageContext);
  if (!context) throw new Error('useLanguage must be used inside LanguageProvider');
  return context;
}

function LanguageSwitcher({ dark = false }) {
  const { language, setLanguage } = useLanguage();
  return (
    <div className={`language-switcher${dark ? ' language-switcher--dark' : ''}`} role="group" aria-label="Language / 言語">
      {['ja', 'en'].map((code) => (
        <button
          className={`language-switcher__option${language === code ? ' is-active' : ''}`}
          type="button"
          key={code}
          onClick={() => setLanguage(code)}
          aria-pressed={language === code}
          lang={code}
        >
          {code.toUpperCase()}
        </button>
      ))}
    </div>
  );
}

window.LanguageProvider = LanguageProvider;
window.LanguageSwitcher = LanguageSwitcher;
window.useLanguage = useLanguage;
