// app.jsx — INDIECASH navigation shell + Tweaks panel

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "dark": false,
  "accent": "emerald",
  "scenario": "couple",
  "hideBalance": false
}/*EDITMODE-END*/;

const ACCENT_PALETTES = [
  ['#10b981', '#059669'], // emerald
  ['#0d9488', '#0f766e'], // teal
  ['#34d399', '#10b981'], // mint
  ['#16a34a', '#15803d'], // forest
];
const ACCENT_NAMES = ['emerald', 'teal', 'mint', 'forest'];

function App() {
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const theme = useTheme(tw.dark, tw.accent);

  // Real auth state from Supabase
  const auth = (typeof useAuth !== 'undefined') ? useAuth() : { loading: false, authReady: true, user: null, profile: null, family: null, signIn: async()=>{}, signOut: async()=>{}, createFamily: async()=>{}, joinFamily: async()=>{} };

  // Derive route from auth state
  const computedRoute = !auth.authReady ? 'loading'
    : !auth.user ? 'login'
    : !auth.profile?.family_id ? 'onboarding'
    : 'app';

  const [route, setRoute] = React.useState('app');     // fallback for demo

  // Sync route with auth
  React.useEffect(() => {
    if (auth.authReady) setRoute(computedRoute);
  }, [computedRoute]);
  const [tab, setTab] = React.useState('home');
  const [sheetOpen, setSheetOpen] = React.useState(false);
  const [sheetKind, setSheetKind] = React.useState('expense');
  const [toast, setToast] = React.useState(null);

  const scenario = SCENARIOS[tw.scenario] || SCENARIOS.couple;

  const openSheet = (kind) => {
    setSheetKind(kind || 'expense');
    setSheetOpen(true);
  };

  const navigate = (target) => {
    if (['home','tx','report','more'].includes(target)) {
      setTab(target);
    } else {
      // sub-screen routes (budget/goals/debts)
      setTab(target);
    }
  };

  const saveTx = async (entry) => {
    // Resolve "Hari ini" / "Kemarin" to ISO date
    var today = new Date();
    var resolvedDate =
      (!entry.date || entry.date === 'Hari ini') ? today.toISOString().split('T')[0] :
      entry.date === 'Kemarin' ? new Date(today.setDate(today.getDate()-1)).toISOString().split('T')[0] :
      entry.date;
    entry = Object.assign({}, entry, { date: resolvedDate });

    if (auth.user && auth.family && window.sbAddTransaction) {
      try {
        // Match category by label name (case-insensitive)
        // entry.cat could be string key ('makan_ex') or null
        var catKey = typeof entry.cat === 'string' ? entry.cat : '';
        var catLabel = (CATEGORIES[catKey] && CATEGORIES[catKey].label) || '';
        var cats = (await window.SB
          .from('categories').select('id,name')
          .or('family_id.is.null,family_id.eq.'+auth.family.id)).data || [];
        var cat = cats.find(function(c){
          return (catLabel && c.name.toLowerCase() === catLabel.toLowerCase()) ||
                 (catKey && c.name.toLowerCase() === catKey.replace(/_/g,' ').toLowerCase());
        });
        var r = await sbAddTransaction(auth.family.id, auth.user.id, Object.assign({}, entry, {
          account_id: entry.account_id || null,
          category_id: cat ? cat.id : null,
        }));
        if (r.error) throw r.error;
      } catch(e) {
        setToast('Error: ' + (e.message||'Gagal simpan'));
        setTimeout(function(){ setToast(null); }, 3000);
        return;
      }
    }
    setToast((entry.kind === 'income' ? '✓ Pemasukan ' : '✓ Pengeluaran ') + fmtRp(entry.amount) + ' tersimpan');
    setTimeout(function(){ setToast(null); }, 2200);
    window.dispatchEvent(new Event('tx-added'));
  };

  // ─── Pick screen based on route + tab ─────────────────────────
  let screen;
  if (route === 'login') {
    screen = <ScreenLogin theme={theme} accent={theme.accent}
                          auth={auth}
                          onContinue={() => setRoute('onboarding')} />;
  } else if (route === 'onboarding') {
    screen = <ScreenOnboarding theme={theme} accent={theme.accent}
                                auth={auth}
                                onPick={() => setRoute('app')} />;
  } else {
    screen = (() => {
      switch (tab) {
        case 'home':   return <ScreenDashboard
                                 theme={theme} accent={theme.accent} scenario={scenario}
                                 auth={auth}
                                 hideBalance={tw.hideBalance}
                                 onToggleHide={() => setTweak('hideBalance', !tw.hideBalance)}
                                 onNavigate={navigate}
                                 onOpenSheet={openSheet} />;
        case 'tx':     return <ScreenTransactions theme={theme} accent={theme.accent}
                                 scenario={scenario} auth={auth} onOpenSheet={openSheet} />;
        case 'report': return <ScreenReport theme={theme} accent={theme.accent} scenario={scenario} auth={auth} />;
        case 'more':   return <ScreenMore   theme={theme} accent={theme.accent} scenario={scenario}
                                 auth={auth}
                                 onNavigate={navigate}
                                 onLogout={async () => { await auth.signOut(); setRoute('login'); }} />;
        case 'budget': return <SubScreen title="Budget" onBack={() => setTab('more')} theme={theme}>
                                <ScreenBudget theme={theme} accent={theme.accent} scenario={scenario} auth={auth} />
                              </SubScreen>;
        case 'goals':  return <SubScreen title="Tabungan" onBack={() => setTab('more')} theme={theme}>
                                <ScreenGoals theme={theme} accent={theme.accent} scenario={scenario} auth={auth} />
                              </SubScreen>;
        case 'debts':  return <SubScreen title="Hutang & Piutang" onBack={() => setTab('more')} theme={theme}>
                                <ScreenDebts theme={theme} accent={theme.accent} scenario={scenario} auth={auth} />
                              </SubScreen>;
        case 'fire':   return <SubScreen title="FIRE Calculator" onBack={() => setTab('more')} theme={theme}>
                                <ScreenFire theme={theme} accent={theme.accent} auth={auth} />
                              </SubScreen>;
        case 'accounts': return <SubScreen title="Kekayaan Bersih" onBack={() => setTab('more')} theme={theme}>
                                <ScreenAccounts theme={theme} accent={theme.accent} auth={auth} />
                               </SubScreen>;
        case 'profile':  return <SubScreen title="Akun Saya" onBack={() => setTab('more')} theme={theme}>
                                <ScreenProfile theme={theme} accent={theme.accent} auth={auth} />
                               </SubScreen>;
        case 'security': return <SubScreen title="Keamanan" onBack={() => setTab('more')} theme={theme}>
                                <ScreenSecurity theme={theme} accent={theme.accent} auth={auth} />
                               </SubScreen>;
        case 'export':   return <SubScreen title="Export Data" onBack={() => setTab('more')} theme={theme}>
                                <ScreenExport theme={theme} accent={theme.accent} auth={auth} />
                               </SubScreen>;
        case 'help':     return <SubScreen title="Bantuan" onBack={() => setTab('more')} theme={theme}>
                                <ScreenHelp theme={theme} accent={theme.accent} />
                               </SubScreen>;
        case 'receipt': return <SubScreen title="Scan Struk" onBack={() => setTab('more')} theme={theme}>
                                <ScreenReceipt theme={theme} accent={theme.accent} scenario={scenario}
                                  onTransactionAdded={(tx) => { setToast('Transaksi dari struk disimpan!'); setTimeout(() => setToast(null), 2200); }} />
                               </SubScreen>;
        default:       return null;
      }
    })();
  }

  const SUB_SCREENS = ['fire','accounts','profile','security','export','help','receipt','budget','goals','debts'];
  const showNav = route === 'app' && !['login','onboarding'].includes(route) && !SUB_SCREENS.includes(tab);
  const statusDark = (route === 'app') ? theme.statusBarDark : theme.statusBarDark;

  return (
    <div style={{
      width: "100%", height: "100%", position: "relative",
      background: theme.bg,
      overflow: 'hidden',
      fontFamily: '"Plus Jakarta Sans", system-ui, -apple-system, sans-serif',
      color: theme.fg1,
    }}
    data-screen-label={
      route === 'login' ? '01 Login'
      : route === 'onboarding' ? '02 Onboarding'
      : ({ home: '03 Dashboard', tx: '04 Transaksi', report: '05 Laporan',
           more: '06 Lainnya', budget: '07 Budget', goals: '08 Tabungan',
           debts: '09 Hutang' }[tab] || tab)
    }>
      {/* Status bar */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, zIndex: 50,
        pointerEvents: 'none',
      }}>
        
      </div>

      {/* Scrollable screen */}
      <div key={route + tab} style={{
        position: 'absolute', inset: 0,
        overflowY: 'auto', overflowX: 'hidden',
        WebkitOverflowScrolling: 'touch',
        animation: 'fade-in 220ms ease-out',
      }}>
        {screen}
      </div>

      {/* Bottom nav (only on app routes) */}
      {showNav && (
        <BottomNav active={tab} onChange={setTab}
                   onFab={() => openSheet('picker')}
                   theme={theme} accent={theme.accent} />
      )}

      {/* FAB picker sheet */}
      {sheetKind === 'picker' && sheetOpen && (
        <FabPicker open={sheetOpen} onClose={() => setSheetOpen(false)}
          onSelect={function(k){ setSheetKind(k); }}
          theme={theme} accent={theme.accent} />
      )}

      {/* Transaction form */}
      {!SUB_SCREENS.includes(tab) && sheetKind !== 'picker' && sheetKind !== 'transfer' && (
        <TxForm open={sheetOpen && sheetKind !== 'transfer'} onClose={() => setSheetOpen(false)}
                onSave={saveTx} auth={auth}
                theme={theme} accent={theme.accent}
                scenario={scenario}
                defaultBy={(scenario.members && scenario.members[0] && scenario.members[0].id) || 'me'} />
      )}

      {/* Transfer form */}
      {!SUB_SCREENS.includes(tab) && (
        <TransferForm open={sheetOpen && sheetKind === 'transfer'} onClose={() => setSheetOpen(false)}
                      onDone={function(){ window.dispatchEvent(new Event('tx-added')); }}
                      auth={auth} theme={theme} accent={theme.accent} />
      )}

      {/* Toast */}
      {toast && (
        <div style={{
          position: 'absolute', left: 16, right: 16, bottom: 110, zIndex: 40,
          padding: '12px 16px', borderRadius: 14,
          background: theme.fg1, color: theme.surface,
          fontSize: 13, fontWeight: 600, letterSpacing: '-0.005em',
          boxShadow: theme.shadow3,
          display: 'flex', alignItems: 'center', gap: 8,
          animation: 'toast-in 240ms ease-out',
        }}>
          <Icon name="check-circle-2" size={16} color={theme.accent[500]} stroke={2.2} />
          {toast}
        </div>
      )}

      {/* Tweaks panel */}
      <TweaksPanel title="INDIECASH · Tweaks">
        <TweakSection label="Tampilan">
          <TweakToggle label="Mode gelap" value={tw.dark}
                       onChange={(v) => setTweak('dark', v)} />
          <TweakColor label="Warna aksen" value={tw.accent}
                      options={[
                        { value: 'emerald', label: 'Emerald' },
                        { value: 'teal',    label: 'Teal' },
                        { value: 'mint',    label: 'Mint' },
                        { value: 'forest',  label: 'Forest' },
                      ].map(o => o.value).reduce((acc, k, i) => {
                        acc.push(ACCENT_PALETTES[i]);
                        return acc;
                      }, [])}
                      onChange={(palette) => {
                        const i = ACCENT_PALETTES.findIndex(
                          (p) => p[0] === palette[0] && p[1] === palette[1]
                        );
                        setTweak('accent', ACCENT_NAMES[i] || 'emerald');
                      }} />
        </TweakSection>
        <TweakSection label="Data demo">
          <TweakSelect label="Skenario" value={tw.scenario}
                       options={[
                         { value: 'couple', label: 'Pasangan muda (2 orang)' },
                         { value: 'young',  label: 'Keluarga muda (3 orang)' },
                         { value: 'mature', label: 'Keluarga dewasa (4 orang)' },
                       ]}
                       onChange={(v) => setTweak('scenario', v)} />
          <TweakToggle label="Sembunyikan saldo" value={tw.hideBalance}
                       onChange={(v) => setTweak('hideBalance', v)} />
        </TweakSection>
        <TweakSection label="Navigasi">
          <TweakSelect label="Mulai dari layar" value={route}
                       options={[
                         { value: 'login',       label: '01 — Login' },
                         { value: 'onboarding',  label: '02 — Onboarding' },
                         { value: 'app',         label: '03+ — App' },
                       ]}
                       onChange={(v) => setRoute(v)} />
          {route === 'app' && (
            <TweakSelect label="Layar app" value={tab}
                         options={[
                           { value: 'home',   label: 'Beranda' },
                           { value: 'tx',     label: 'Transaksi' },
                           { value: 'report', label: 'Laporan' },
                           { value: 'more',   label: 'Lainnya' },
                           { value: 'budget', label: 'Budget' },
                           { value: 'goals',  label: 'Tabungan' },
                           { value: 'debts',  label: 'Hutang' },
                         ]}
                         onChange={(v) => setTab(v)} />
          )}
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

// Sub-screen wrapper — adds a back row above content
function SubScreen({ title, onBack, theme, children }) {
  // The inner screens already render their own large title in 56px-top padding.
  // To keep visual consistency we just overlay a back button in the same zone.
  return (
    <div style={{ position: 'relative' }}>
      <button onClick={onBack} style={{
        position: 'absolute', top: 56, left: 14, zIndex: 5,
        appearance: 'none', border: 0, cursor: 'pointer',
        width: 38, height: 38, borderRadius: 12,
        background: theme.surface,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: theme.shadow1,
        border: `0.5px solid ${theme.border}`,
      }}>
        <Icon name="arrow-left" size={18} color={theme.fg1} stroke={1.8} />
      </button>
      {/* Pad the screen header right slightly so it doesn't sit under back btn */}
      <div style={{ paddingLeft: 48 }}>{children}</div>
    </div>
  );
}

// Faux status bar — same look as iOS frame's, but lives inside the screen so
// the dark/light icons can react to scenario/dark-mode.
function FakeStatusBar({ dark }) {
  const c = dark ? '#fff' : '#0f172a';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '16px 28px 8px', boxSizing: 'border-box', height: 44,
    }}>
      <span style={{
        fontFamily: '-apple-system, "SF Pro", system-ui',
        fontWeight: 600, fontSize: 15, color: c,
      }}>9:41</span>
      <div style={{ display: 'flex', gap: 5, alignItems: 'center' }}>
        <svg width="17" height="11" viewBox="0 0 17 11">
          <rect x="0"  y="6"  width="3" height="5" rx="0.6" fill={c}/>
          <rect x="4.5" y="4" width="3" height="7" rx="0.6" fill={c}/>
          <rect x="9"   y="2" width="3" height="9" rx="0.6" fill={c}/>
          <rect x="13.5" y="0" width="3" height="11" rx="0.6" fill={c}/>
        </svg>
        <svg width="15" height="11" viewBox="0 0 15 11">
          <path d="M7.5 2.8C9.5 2.8 11.3 3.6 12.7 4.9L13.7 4C12 2.4 9.8 1.4 7.5 1.4C5.2 1.4 3 2.4 1.3 4L2.3 4.9C3.7 3.6 5.5 2.8 7.5 2.8Z" fill={c}/>
          <path d="M7.5 6C8.7 6 9.8 6.5 10.6 7.3L11.6 6.3C10.5 5.2 9.1 4.5 7.5 4.5C5.9 4.5 4.5 5.2 3.4 6.3L4.4 7.3C5.2 6.5 6.3 6 7.5 6Z" fill={c}/>
          <circle cx="7.5" cy="9.4" r="1.3" fill={c}/>
        </svg>
        <svg width="24" height="11" viewBox="0 0 24 11">
          <rect x="0.5" y="0.5" width="21" height="10" rx="3" stroke={c} strokeOpacity="0.45" fill="none"/>
          <rect x="2"   y="2"   width="14" height="7" rx="1.5" fill={c}/>
          <path d="M22.5 4v3c0.7 -0.3 1.2 -1 1.2 -1.5C23.7 5 23.2 4.3 22.5 4Z" fill={c} fillOpacity="0.45"/>
        </svg>
      </div>
    </div>
  );
}

// Mount
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Object.assign(window, { App, SubScreen, FakeStatusBar });
