// Main app — routes between screens, provides Tweaks

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "yellow",
  "density": "comfortable",
  "dark": false,
  "accentGlyph": true,
  "illustrationStyle": "placeholder"
}/*EDITMODE-END*/;

function App() {
  const [tab, setTab] = React.useState('home');
  const [view, setView] = React.useState({ type: 'tab' });  // or { type: 'detail', drink }
  const [showSearch, setShowSearch] = React.useState(false);
  const [log, setLog] = React.useState([]);
  const [tweaks, setTweaks] = React.useState(TWEAK_DEFAULTS);
  const [tweaksOpen, setTweaksOpen] = React.useState(false);
  const [detailState, setDetailState] = React.useState({ totalCal: 0, totalSugar: 0 });
  const [libraryBrand, setLibraryBrand] = React.useState('all');

  // edit mode wiring
  React.useEffect(() => {
    const onMessage = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTweaksOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksOpen(false);
    };
    window.addEventListener('message', onMessage);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMessage);
  }, []);

  const setTweak = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
  };

  const openDrink = (drink) => setView({ type: 'detail', drink });
  const openAction = (kind) => setView({ type: 'action', kind });
  const openCollab = (collab) => setView({ type: 'collab', collab });
  const openCollabAll = () => setView({ type: 'collab-all' });
  const backToTab = () => setView({ type: 'tab' });

  const ACTION_KINDS = new Set(['pick', 'shuffle', 'avoid', 'samecheck']);

  const handleNav = (dest) => {
    if (ACTION_KINDS.has(dest)) openAction(dest);
    else if (dest === 'library') { setLibraryBrand('all'); setTab('library'); }
    else if (dest === 'brand')   { setLibraryBrand('all'); setTab('library'); }
    else if (dest === 'favorite') setTab('favorite');
    // fall-through: no-op instead of silently opening a random drink
  };

  const openLibraryWithBrand = (brand) => {
    setLibraryBrand(brand?.id || 'all');
    setTab('library');
  };

  const handleTabChange = (t) => {
    if (t === 'library') setLibraryBrand('all');
    setTab(t);
  };

  let screen;
  if (view.type === 'detail') {
    screen = <DrinkDetailScreen drink={view.drink} onBack={backToTab}
              onStateChange={setDetailState} />;
  } else if (view.type === 'collab') {
    screen = <CollabDetailScreen collab={view.collab} onBack={backToTab} onOpenDrink={openDrink} />;
  } else if (view.type === 'collab-all') {
    screen = <CollabAllScreen onBack={backToTab} onOpenCollab={openCollab} />;
  } else if (view.type === 'action') {
    if (view.kind === 'pick') {
      screen = <PickForMeScreen onBack={backToTab} onOpenDrink={openDrink} />;
    } else if (view.kind === 'shuffle') {
      screen = <ShuffleItScreen onBack={backToTab} onOpenDrink={openDrink} />;
    } else if (view.kind === 'avoid') {
      screen = <AvoidMissesScreen onBack={backToTab} onOpenDrink={openDrink} />;
    } else if (view.kind === 'samecheck') {
      screen = <SameCheckScreen onBack={backToTab} onOpenDrink={openDrink} />;
    }
  } else if (tab === 'home') {
    screen = <HomeScreen
              onOpenSearch={() => setShowSearch(true)}
              onNav={handleNav}
              onOpenBrand={openLibraryWithBrand}
              onOpenCollab={openCollab}
              onOpenAllCollabs={openCollabAll}
              onOpenDrink={openDrink} />;
  } else if (tab === 'library') {
    screen = <LibraryScreen key={libraryBrand} initialBrand={libraryBrand} onOpenDrink={openDrink} />;
  } else if (tab === 'favorite') {
    screen = <FavoriteScreen onOpenDrink={openDrink} />;
  } else if (tab === 'me') {
    screen = <MeScreen logEntries={log} />;
  }

  return (
    <div data-theme={tweaks.theme} data-density={tweaks.density}
         data-mode={tweaks.dark ? 'dark' : 'light'}
         style={{ width: '100%', height: '100%', position: 'relative',
                  background: 'var(--paper)', overflow: 'hidden' }}>
      <div style={{ width: '100%', height: '100%', overflowY: 'auto', overflowX: 'hidden',
                    position: 'relative' }}>
        {screen}
      </div>
      {view.type === 'tab' && <TabBar active={tab} onChange={handleTabChange} />}
      {view.type === 'detail' && (
        <DetailStickyCTA
          drink={view.drink}
          totalCal={detailState.totalCal}
          onAdd={() => setLog([...log, { drink: view.drink, ...detailState }])} />
      )}
      {view.type === 'action' && <TabBar active={tab} onChange={(t) => { setView({ type: 'tab' }); handleTabChange(t); }} />}
      {showSearch && <SearchOverlay onClose={() => setShowSearch(false)} onOpenDrink={openDrink} />}

      {tweaksOpen && <TweaksPanel tweaks={tweaks} setTweak={setTweak} onClose={() => setTweaksOpen(false)} />}
    </div>
  );
}

function TweaksPanel({ tweaks, setTweak, onClose }) {
  return (
    <div style={{
      position: 'fixed', right: 16, bottom: 16, width: 280, zIndex: 2000,
      background: 'rgba(28,23,16,0.95)', color: '#fff', borderRadius: 20,
      padding: 16, backdropFilter: 'blur(20px)',
      boxShadow: '0 20px 60px rgba(0,0,0,0.3)',
      fontFamily: 'var(--font-sans)', fontSize: 12,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
        <span style={{ fontWeight: 600, fontSize: 13 }}>Tweaks</span>
        <button onClick={onClose} style={{ color: 'rgba(255,255,255,0.6)' }}>
          <IconX size={14} color="currentColor" />
        </button>
      </div>
      <TwRow label="主题色">
        <div style={{ display: 'flex', gap: 6 }}>
          {['yellow', 'purple', 'matcha'].map(t => (
            <button key={t} onClick={() => setTweak('theme', t)} style={{
              width: 30, height: 30, borderRadius: 999,
              background: { yellow: '#FFC94D', purple: '#A78BFA', matcha: '#9FCC85' }[t],
              border: tweaks.theme === t ? '2px solid #fff' : '2px solid transparent',
            }} />
          ))}
        </div>
      </TwRow>
      <TwRow label="卡片密度">
        {['comfortable', 'compact'].map(d => (
          <button key={d} onClick={() => setTweak('density', d)} style={{
            padding: '6px 10px', borderRadius: 999, fontSize: 11,
            background: tweaks.density === d ? '#fff' : 'transparent',
            color: tweaks.density === d ? '#000' : 'rgba(255,255,255,0.7)',
            border: '0.5px solid rgba(255,255,255,0.2)', marginRight: 6,
          }}>{d === 'comfortable' ? '舒适' : '紧凑'}</button>
        ))}
      </TwRow>
      <TwRow label="深色模式">
        <button onClick={() => setTweak('dark', !tweaks.dark)} style={{
          width: 36, height: 20, borderRadius: 999,
          background: tweaks.dark ? 'var(--brand-yellow)' : 'rgba(255,255,255,0.2)',
          position: 'relative', transition: 'background 200ms',
        }}>
          <div style={{ position: 'absolute', top: 2, left: tweaks.dark ? 18 : 2,
                        width: 16, height: 16, borderRadius: 999, background: '#fff',
                        transition: 'left 200ms' }} />
        </button>
      </TwRow>
      <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.5)', marginTop: 14, lineHeight: 1.5 }}>
        提示：在工具栏顶部切换 Tweaks 开关可关闭此面板
      </div>
    </div>
  );
}

function TwRow({ label, children }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  padding: '8px 0', borderTop: '0.5px solid rgba(255,255,255,0.1)' }}>
      <span style={{ color: 'rgba(255,255,255,0.7)' }}>{label}</span>
      <div style={{ display: 'flex', alignItems: 'center' }}>{children}</div>
    </div>
  );
}

// ───── Mount ─────
function Mount() {
  // Use IOSDevice as the phone frame (its status bar is correct; we put our own
  // mini-program chrome inside via MpChrome)
  const [scale, setScale] = React.useState(1);
  React.useEffect(() => {
    const update = () => {
      const vw = window.innerWidth, vh = window.innerHeight;
      const fw = 402, fh = 874;
      const s = Math.min(vw / fw, vh / fh, 1) * 0.96;
      setScale(s);
    };
    update();
    window.addEventListener('resize', update);
    return () => window.removeEventListener('resize', update);
  }, []);
  const FW = 402, FH = 874;
  return (
    <div style={{
      minHeight: '100vh', width: '100%',
      background: 'radial-gradient(ellipse at center top, #FFF5E0, #F4ECD8 60%, #EADFBF)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden',
    }}>
      <div style={{ width: FW * scale, height: FH * scale, position: 'relative' }}>
        <div style={{ transform: `scale(${scale})`, transformOrigin: 'top left',
                      position: 'absolute', top: 0, left: 0 }}>
          <IOSDevice width={FW} height={FH}>
            <App />
          </IOSDevice>
        </div>
      </div>
    </div>
  );
}

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