/* Central Rewards Club — root app: router, tabs, store wiring, responsive shell. */
const { useState, useEffect, useRef } = React;

const ACCENTS = {
  '#7A1F2B': { dark: '#4D1019', soft: '#F3E7E9' },
  '#1F6E47': { dark: '#134029', soft: '#E4F0EA' },
  '#243A66': { dark: '#14223D', soft: '#E7ECF5' },
  '#2A2A2A': { dark: '#141414', soft: '#ECECEC' },
};

const PUSH_TITLES = {
  notifications: 'Notifikasi', history: 'Riwayat transaksi',
  settings: 'Pengaturan', vouchers: 'Voucher saya',
};
const FLOATING = new Set(['rewardDetail', 'promoDetail', 'social', 'events']);

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#7A1F2B",
  "tier": "gold",
  "displayFont": true
}/*EDITMODE-END*/;

// phone-sized viewport → render fullscreen (real PWA); larger → device frame.
const isPhoneViewport = () => window.matchMedia('(max-width: 480px)').matches;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [store, actions] = useCRCStore();
  const C = window.CRC;

  const [onboarded, setOnboarded] = useState(false);
  const [tab, setTab] = useState('home');
  const [stack, setStack] = useState([]); // [{screen, params}]
  const [sheet, setSheet] = useState(null);
  const [toast, setToast] = useState(null);
  const [celebrate, setCelebrate] = useState(false);

  const points = store.points;

  // Deep-link from PWA shortcuts (?tab=earn) — after onboarding.
  useEffect(() => {
    const q = new URLSearchParams(window.location.search).get('tab');
    if (q && ['home', 'rewards', 'earn', 'promos', 'profile'].includes(q)) { setOnboarded(true); setTab(q); }
  }, []);

  // Apply accent + tier CSS vars
  useEffect(() => {
    const a = ACCENTS[t.accent] || ACCENTS['#7A1F2B'];
    const r = document.documentElement.style;
    r.setProperty('--crc-primary', t.accent);
    r.setProperty('--crc-primary-dark', a.dark);
    r.setProperty('--crc-primary-soft', a.soft);
    const T = C.TIERS[t.tier];
    r.setProperty('--crc-tier', T.accent);
    r.setProperty('--crc-tier-deep', T.accentDeep);
    r.setProperty('--crc-display', t.displayFont ? "'Playfair Display', Georgia, serif" : "'Inter', sans-serif");
  }, [t.accent, t.tier, t.displayFont]);

  const member = { ...C.member, tier: t.tier, points: store.points, ytdSpend: store.ytdSpend };
  const tierObj = C.TIERS[t.tier];

  const showToast = (msg, type = 'success') => { setToast({ msg, type }); setTimeout(() => setToast(null), 2600); };
  const flash = () => { setCelebrate(true); setTimeout(() => setCelebrate(false), 1600); };
  const earn = (n) => { actions.earn(n); if (n > 0) flash(); };

  const ctx = {
    C, member, tier: t.tier, tierObj, points, fmt: C.fmt,
    store, actions,
    setTab: (x) => { setStack([]); setTab(x); },
    push: (screen, params) => setStack((s) => [...s, { screen, params }]),
    pop: () => setStack((s) => s.slice(0, -1)),
    openSheet: (node, opts) => setSheet({ node, ...opts }),
    closeSheet: () => setSheet(null),
    toast: showToast, earn, celebrate: flash,
    replayOnboarding: () => { setOnboarded(false); setStack([]); setTab('home'); },
    resetData: (profile) => { actions.reset(profile); setStack([]); setTab('home'); showToast(profile === 'new' ? 'Data demo di-reset (member baru)' : 'Data demo di-reset (aktif)', 'info'); },
  };

  // ── Onboarding gate ──
  if (!onboarded) {
    return (
      <Shell t={t} setTweak={setTweak} ctx={ctx}>
        <div className="crc-app" style={{ height: '100%', position: 'relative' }}>
          <Onboarding onComplete={() => setOnboarded(true)} />
        </div>
      </Shell>
    );
  }

  const TABS = [
    { k: 'home', icon: 'home', label: 'Beranda' },
    { k: 'rewards', icon: 'gift', label: 'Hadiah' },
    { k: 'earn', icon: 'scan', label: 'Scan', center: true },
    { k: 'promos', icon: 'tag', label: 'Promo' },
    { k: 'profile', icon: 'user', label: 'Profil' },
  ];
  const TAB_SCREENS = { home: Home, rewards: Rewards, earn: EarnScreen, promos: Promos, profile: Profile };
  const PUSH_SCREENS = { social: Social, notifications: Notifications, history: History, events: Events, settings: Settings, vouchers: Vouchers, rewardDetail: RewardDetail, promoDetail: PromoDetail };

  const TabComp = TAB_SCREENS[tab];
  const earnFull = tab === 'earn';

  return (
   <Shell t={t} setTweak={setTweak} ctx={ctx}>
    <div className="crc-app" style={{ height: '100%', position: 'relative', overflow: 'hidden', background: earnFull && stack.length === 0 ? '#15080b' : 'var(--crc-bg)' }}>
      {/* Base tab content */}
      <div style={{ position: 'absolute', inset: 0, overflowY: 'auto', paddingBottom: earnFull ? 0 : 96 }}>
        <TabComp ctx={ctx} />
      </div>

      {/* Pushed screens */}
      {stack.map((entry, i) => {
        const Comp = PUSH_SCREENS[entry.screen];
        const floating = FLOATING.has(entry.screen);
        return (
          <div key={i} style={{ position: 'absolute', inset: 0, background: 'var(--crc-bg)', overflowY: 'auto', animation: 'crc-slide-in .3s cubic-bezier(.2,.8,.2,1)', zIndex: 50 + i }}>
            {floating ? (
              <button onClick={ctx.pop} style={floatBtn}><CRCIcon name="chevL" size={22} /></button>
            ) : (
              <div style={pushHeader}>
                <button onClick={ctx.pop} style={{ width: 40, height: 40, borderRadius: 12, border: 'none', background: 'var(--crc-bg)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}><CRCIcon name="chevL" size={20} /></button>
                <span style={{ fontWeight: 700, fontSize: 17 }}>{PUSH_TITLES[entry.screen] || ''}</span>
                <span style={{ width: 40 }} />
              </div>
            )}
            <div style={{ paddingBottom: 30 }}><Comp ctx={ctx} params={entry.params} /></div>
          </div>
        );
      })}

      {/* Bottom tab bar */}
      {stack.length === 0 && (
        <div style={tabBar}>
          {TABS.map((tb) => {
            const active = tab === tb.k;
            if (tb.center) return (
              <button key={tb.k} onClick={() => ctx.setTab(tb.k)} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--crc-font)', marginTop: -22 }}>
                <span style={{ width: 56, height: 56, borderRadius: 19, background: active ? 'var(--crc-ink)' : 'linear-gradient(135deg,var(--crc-primary),var(--crc-primary-dark))', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 8px 20px rgba(122,31,43,.4)' }}><CRCIcon name="scan" size={26} stroke={2.2} /></span>
                <span style={{ fontSize: 10.5, fontWeight: 600, color: active ? 'var(--crc-primary)' : 'var(--crc-ink-2)', marginTop: 4 }}>{tb.label}</span>
              </button>
            );
            return (
              <button key={tb.k} onClick={() => ctx.setTab(tb.k)} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--crc-font)', paddingTop: 4 }}>
                <CRCIcon name={tb.icon} size={24} color={active ? 'var(--crc-primary)' : 'var(--crc-ink-2)'} stroke={active ? 2.3 : 2} fill={active ? 'var(--crc-primary-soft)' : 'none'} />
                <span style={{ fontSize: 10.5, fontWeight: active ? 700 : 600, color: active ? 'var(--crc-primary)' : 'var(--crc-ink-2)' }}>{tb.label}</span>
              </button>
            );
          })}
        </div>
      )}

      <BottomSheet open={!!sheet} onClose={ctx.closeSheet} height={sheet?.height} full={sheet?.full}>{sheet?.node}</BottomSheet>
      <Toast toast={toast} />
      <Confetti show={celebrate} />
    </div>
   </Shell>
  );
}

// ── Device stage: fullscreen on phones (real PWA), scaled iPhone on desktop ──
function DeviceStage({ children }) {
  const [phone, setPhone] = useState(isPhoneViewport());
  const [scale, setScale] = useState(1);
  useEffect(() => {
    const fit = () => {
      const p = isPhoneViewport();
      setPhone(p);
      if (!p) setScale(Math.min((window.innerWidth - 28) / 402, (window.innerHeight - 28) / 874));
    };
    fit();
    window.addEventListener('resize', fit);
    const mq = window.matchMedia('(max-width: 480px)');
    mq.addEventListener && mq.addEventListener('change', fit);
    return () => { window.removeEventListener('resize', fit); mq.removeEventListener && mq.removeEventListener('change', fit); };
  }, []);

  // Real phone / installed PWA → fill the viewport, no bezel.
  if (phone) {
    return (
      <div style={{ position: 'fixed', inset: 0, background: 'var(--crc-bg)', overflow: 'hidden' }}>
        {children}
      </div>
    );
  }
  // Desktop / tablet → centered premium device frame (still the mobile view).
  return (
    <div style={{ position: 'fixed', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'radial-gradient(120% 120% at 50% 0%, #efece8 0%, #e2ded9 100%)', overflow: 'hidden' }}>
      <div style={{ transform: `scale(${scale})`, transformOrigin: 'center center' }}>
        <IOSDevice>{children}</IOSDevice>
      </div>
    </div>
  );
}

function Shell({ children, t, setTweak, ctx }) {
  return (
    <React.Fragment>
      <DeviceStage>{children}</DeviceStage>
      <TweaksUI t={t} setTweak={setTweak} ctx={ctx} />
    </React.Fragment>
  );
}

const tabBar = {
  position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 100,
  display: 'flex', alignItems: 'flex-start', padding: '12px 12px calc(26px + var(--crc-safe-bottom, 0px))',
  background: 'rgba(255,255,255,.92)', backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
  borderTop: '1px solid var(--crc-line-soft)', boxShadow: '0 -4px 20px rgba(0,0,0,.04)',
};
const floatBtn = {
  position: 'absolute', top: 'calc(54px + var(--crc-safe-top, 0px))', left: 16, zIndex: 10, width: 42, height: 42, borderRadius: '50%',
  border: 'none', background: 'rgba(255,255,255,.92)', backdropFilter: 'blur(8px)',
  boxShadow: '0 4px 14px rgba(0,0,0,.18)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
};
const pushHeader = {
  position: 'sticky', top: 0, zIndex: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
  padding: 'calc(54px + var(--crc-safe-top, 0px)) 16px 12px', background: 'rgba(250,250,250,.9)', backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
  borderBottom: '1px solid var(--crc-line-soft)',
};

// ── Tweaks panel UI (demo controls) ──
function TweaksUI({ t, setTweak, ctx }) {
  return (
    <TweaksPanel>
      <TweakSection label="Brand" />
      <TweakColor label="Aksen utama" value={t.accent}
        options={['#7A1F2B', '#1F6E47', '#243A66', '#2A2A2A']}
        onChange={(v) => setTweak('accent', v)} />
      <TweakToggle label="Font display Playfair" value={t.displayFont} onChange={(v) => setTweak('displayFont', v)} />
      <TweakSection label="Member" />
      <TweakSelect label="Tier" value={t.tier}
        options={[{ value: 'classic', label: 'Classic' }, { value: 'gold', label: 'Gold' }, { value: 'platinum', label: 'Platinum' }, { value: 'black', label: 'Central Black' }]}
        onChange={(v) => setTweak('tier', v)} />
      <TweakSection label="Demo data" />
      <TweakButton label="Reset — member aktif" onClick={() => ctx.resetData('active')} />
      <TweakButton label="Reset — member baru" onClick={() => ctx.resetData('new')} />
      <TweakButton label="Putar ulang onboarding" onClick={ctx.replayOnboarding} />
    </TweaksPanel>
  );
}

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