/* global React, ReactDOM, window */
// Vibramood · app.jsx — composition + tweaks + sheet/toast.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "device": "tablet",
  "color": "natural",
  "wallpaper": "default",
  "secondary": "none",
  "screen": "map",
  "mood": "khawatir",
  "intensity": 35,
  "biome": "woods",
  "journalView": "journal",
  "onbPick": "tito",
  "audio": true,
  "lowStim": false,
  "bigFont": false,
  "motion": true,
  "time": "9:41"
}/*EDITMODE-END*/;

const { useTweaks, TweaksPanel, TweakSection, TweakSelect, TweakSegment, TweakText, TweakToggle,
        DeviceFrame, MobileShell, BottomTabs, Sheet, Toast, Icon } = window.WFMobile;
const { Vibra } = window.VMVibras;
const { VMHeader, ScreenOnboarding, ScreenCheckin, ScreenMap, ScreenBiome, ScreenJournal } = window.VMScreens;

function App() {
  const [t, setT] = useTweaks(TWEAK_DEFAULTS);
  const [name, setName] = React.useState(window.VM.player.name);
  const [sheet, setSheet] = React.useState(null);
  const [toast, setToast] = React.useState(null);

  React.useEffect(() => {
    if (!toast) return;
    const id = setTimeout(() => setToast(null), 2400);
    return () => clearTimeout(id);
  }, [toast]);

  const tabs = [
    { key: 'map',      label: 'Peta',      icon: 'mapPin',  iconFill: 'mapPin' },
    { key: 'checkin',  label: 'Cek Mood',  icon: 'sparkle', iconFill: 'sparkle' },
    { key: 'biome',    label: 'Aktivitas', icon: 'leaf',    iconFill: 'leaf' },
    { key: 'journal',  label: 'Jurnal',    icon: 'gift',    iconFill: 'giftFill' },
    { key: 'profile',  label: 'Profil',    icon: 'user',    iconFill: 'userFill' },
  ];

  const onFinishBiome = () => {
    setSheet({ kind: 'reward' });
  };

  const renderScreen = () => {
    switch (t.screen) {
      case 'onboarding':
        return <ScreenOnboarding
          pick={t.onbPick}
          onPick={(k) => setT('onbPick', k)}
          name={name}
          onName={setName}
          onContinue={() => { setT('screen', 'checkin'); setToast('Selamat datang, ' + (name || 'teman') + '!'); }}
        />;
      case 'checkin':
        return <ScreenCheckin
          mood={t.mood}
          onMood={(m) => setT('mood', m)}
          intensity={t.intensity}
          onIntensity={(v) => setT('intensity', v)}
          onConfirm={() => {
            const mood = window.VM.findMood(t.mood);
            setT('biome', mood.biome);
            setT('screen', 'map');
            setToast('Mood tersimpan · disarankan: ' + window.VM.findBiome(mood.biome).name);
          }}
        />;
      case 'biome':
        return <ScreenBiome biomeKey={t.biome} onFinish={onFinishBiome}/>;
      case 'journal':
        return <ScreenJournal view={t.journalView} onView={(v) => setT('journalView', v)}/>;
      case 'profile':
        return (
          <div className="wm-stack" style={{ padding: '16px 18px' }}>
            <div className="vm-checkin-hero">
              <div className="greeting">PROFIL</div>
              <div className="ask">Halo, {name}</div>
            </div>
            <div className="vm-mood-card">
              <div className="face"><Vibra which={window.VM.player.companion} size={44}/></div>
              <div className="copy">
                <div className="day">Sahabat Vibra</div>
                <div className="note">Tito · ditemui hari ini</div>
              </div>
              <div className="badge" style={{ '--mood-color': 'var(--vm-aqua-700)', '--mood-tint': 'var(--vm-aqua-50)' }}>Aktif</div>
            </div>
            <div className="vm-summary">
              <div className="ico"><Icon name="leaf" size={18} color="#fff"/></div>
              <div className="body">
                <div className="ttl">Daun & Streak</div>
                <div className="sub">{window.VM.player.leaves} daun · hari ke-{window.VM.player.streak} berturut-turut.</div>
              </div>
            </div>
          </div>
        );
      default:
        return <ScreenMap onOpenBiome={(b) => { setT('biome', b); setT('screen', 'biome'); }} recommendedKey={window.VM.findMood(t.mood)?.biome || 'woods'}/>;
    }
  };

  const showShellHeader = t.screen !== 'onboarding';
  const showTabs = t.screen !== 'onboarding';
  const wallpaper = t.wallpaper;

  const appClass = 'vm-app-static' + (t.lowStim ? ' vm-low-stim' : '') + (t.bigFont ? ' vm-big' : '');
  // motion toggle: when false, add same class as low-stim's static behavior
  const motionClass = t.motion ? '' : ' vm-app-static';

  const screen = (
    <MobileShell
      header={showShellHeader ? <VMHeader audio={t.audio} onAudio={() => setT('audio', !t.audio)} onSettings={() => setToast('Pengaturan dummy')}/> : null}
      tabs={showTabs ? <BottomTabs items={tabs} active={t.screen === 'biome' ? 'biome' : t.screen} onChange={(k) => setT('screen', k)}/> : null}
      sheet={
        <Sheet
          open={!!sheet}
          title="Kamu menemukan Fern!"
          onClose={() => setSheet(null)}
          footer={
            <div className="wm-stack-sm">
              <button className="wm-btn brand full" onClick={() => { setSheet(null); setT('screen', 'journal'); setT('journalView', 'collection'); setToast('Fern ditambahkan ke koleksi'); }}>
                Lihat Koleksi
              </button>
              <button className="wm-btn ghost full" onClick={() => setSheet(null)}>Nanti saja</button>
            </div>
          }
        >
          <div className="wm-stack-sm" style={{ alignItems: 'center', textAlign: 'center' }}>
            <Vibra which="fern" size={120}/>
            <div className="wm-h3">Fern · Vibra Daun Lembut</div>
            <div className="wm-muted" style={{ fontSize: 13, maxWidth: 280 }}>
              Fern muncul saat kamu bernapas dengan tenang di Whisper Woods. Dia akan menemanimu saat khawatir datang lagi.
            </div>
            <div className="vm-summary" style={{ width: '100%' }}>
              <div className="ico"><Icon name="leaf" size={18} color="#fff"/></div>
              <div className="body">
                <div className="ttl">+5 daun</div>
                <div className="sub">Total kamu sekarang: {window.VM.player.leaves + 5} daun</div>
              </div>
            </div>
          </div>
        </Sheet>
      }
      toast={toast ? <Toast message={toast}/> : null}
    >
      <div className={appClass + motionClass} data-vm>
        {renderScreen()}
      </div>
    </MobileShell>
  );

  const secondaryDevice = t.secondary !== 'none' ? t.secondary : null;

  // Attach low-stim / bigFont classes to root .wm-app via wallpaper prop hack? We'll set on inner wrapper above.

  return (
    <>
      <DeviceFrame
        device={t.device}
        color={t.color}
        wallpaper={wallpaper}
        time={t.time}
        secondary={secondaryDevice}
      >
        {screen}
      </DeviceFrame>

      <TweaksPanel title="Vibramood · Mobile">
        <TweakSection label="Device" />
        <TweakSegment label="Frame" value={t.device} onChange={(v) => setT('device', v)}
          options={[{ value: 'tablet', label: 'iPad' }, { value: 'iphone', label: 'iPhone' }, { value: 'android', label: 'Android' }]} />
        <TweakSelect label="Warna Bezel" value={t.color} onChange={(v) => setT('color', v)}
          options={t.device === 'iphone'
            ? [{ value: 'natural', label: 'Natural Titanium' }, { value: 'black', label: 'Black Titanium' }, { value: 'desert', label: 'Desert Titanium' }]
            : t.device === 'android'
              ? [{ value: 'obsidian', label: 'Obsidian' }, { value: 'porcelain', label: 'Porcelain' }]
              : [{ value: 'natural', label: 'Space Black' }]
          } />
        <TweakSelect label="Tampilkan Kedua" value={t.secondary} onChange={(v) => setT('secondary', v)}
          options={[{ value: 'none', label: 'Tidak ada' }, { value: 'iphone', label: 'iPhone' }, { value: 'android', label: 'Android' }, { value: 'tablet', label: 'iPad' }]} />
        <TweakSelect label="Wallpaper Stage" value={t.wallpaper} onChange={(v) => setT('wallpaper', v)}
          options={[
            { value: 'default', label: 'Soft Cream' },
            { value: 'white', label: 'White' },
            { value: 'plain', label: 'Plain' },
            { value: 'sand', label: 'Warm Sand' },
            { value: 'sunset', label: 'Bali Sunset' },
            { value: 'grid', label: 'Grid' },
          ]} />
        <TweakText label="Jam Status" value={t.time} onChange={(v) => setT('time', v)} placeholder="9:41"/>

        <TweakSection label="Konten" />
        <TweakSegment label="Layar" value={t.screen} onChange={(v) => setT('screen', v)}
          options={[
            { value: 'onboarding', label: 'Intro' },
            { value: 'checkin', label: 'Cek' },
            { value: 'map', label: 'Peta' },
            { value: 'biome', label: 'Biome' },
            { value: 'journal', label: 'Jurnal' },
          ]} />
        <TweakSelect label="Mood Aktif" value={t.mood} onChange={(v) => setT('mood', v)}
          options={window.VM.moods.map((m) => ({ value: m.key, label: m.label }))} />
        <TweakSelect label="Biome" value={t.biome} onChange={(v) => setT('biome', v)}
          options={window.VM.biomes.map((b) => ({ value: b.key, label: b.name }))} />
        <TweakSegment label="Jurnal" value={t.journalView} onChange={(v) => setT('journalView', v)}
          options={[{ value: 'journal', label: 'Mood' }, { value: 'collection', label: 'Koleksi' }]} />

        <TweakSection label="Aksesibilitas" />
        <TweakToggle label="Audio" value={t.audio} onChange={(v) => setT('audio', v)} />
        <TweakToggle label="Animasi" value={t.motion} onChange={(v) => setT('motion', v)} />
        <TweakToggle label="Low-Stim Mode" value={t.lowStim} onChange={(v) => setT('lowStim', v)} />
        <TweakToggle label="Teks Besar" value={t.bigFont} onChange={(v) => setT('bigFont', v)} />
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
setTimeout(() => window.postMessage({ type: '__activate_edit_mode' }, '*'), 200);
