// lvpai-app.jsx — 应用根：状态 / 路由 / 底部导航 / Tweaks
const LVT = window.LV_T;
const { useTweaks, TweaksPanel, TweakSection, TweakColor, TweakRadio } = window;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#1A1916",
  "stageBg": "#161512",
  "demoStage": "照片已到",
  "scene": "1 拍摄完 / 绑卡后"
}/*EDITMODE-END*/;

// 转化场景 → CONVERT_SCENES key
const SCENE_MAP = {
  '1 拍摄完 / 绑卡后': 's1',
  '2 取片点现场加购': 's2',
  '3 当晚推送': 's3',
  '4 一周后推送': 's4'
};

const STAGE_MAP = {
  '未绑卡':   { bound: false, stage: 'unbound' },
  '上传中':   { bound: true,  stage: 'uploading' },
  '照片已到': { bound: true,  stage: 'arrived' },
  '已领免费': { bound: true,  stage: 'claimed' },
  '已购整组': { bound: true,  stage: 'bought' },
};

function makeInitialPhotos(stage) {
  const g = window.LV_DATA.PHOTO_GROUP;
  const ph = {};
  if (stage === 'claimed') ph[g.photos[0].id] = 'free';
  if (stage === 'bought') g.photos.forEach(p => ph[p.id] = 'bought');
  return ph;
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  window.__LVACCENT = t.accent;

  const D = window.LV_DATA;
  const initStage = STAGE_MAP[t.demoStage] || STAGE_MAP['照片已到'];
  const [store, setStore] = React.useState(() => ({
    bound: initStage.bound,
    stage: initStage.stage,
    photos: makeInitialPhotos(initStage.stage),
    group: D.PHOTO_GROUP,
    orders: D.ORDERS_SEED.map(o => ({ ...o })),
  }));

  // demoStage tweak -> reset flow state
  const lastDemo = React.useRef(t.demoStage);
  React.useEffect(() => {
    if (t.demoStage !== lastDemo.current) {
      lastDemo.current = t.demoStage;
      const s = STAGE_MAP[t.demoStage];
      setStore(prev => ({ ...prev, bound: s.bound, stage: s.stage, photos: makeInitialPhotos(s.stage) }));
    }
  }, [t.demoStage]);

  const [tab, setTab] = React.useState('home');
  const [stack, setStack] = React.useState([]);

  // ── 转化场景（Tweak 驱动）──
  const sceneKey = SCENE_MAP[t.scene] || 's1';
  const scene = D.CONVERT_SCENES[sceneKey];
  const [push, setPush] = React.useState(false);
  React.useEffect(() => {
    setStack([]);
    if (sceneKey === 's3' || sceneKey === 's4') {
      setPush(false);
      const to = setTimeout(() => setPush(true), 700);
      return () => clearTimeout(to);
    }
    setPush(false);
  }, [sceneKey]);

  const storeApi = {
    ...store,
    set: (partial) => setStore(prev => ({ ...prev, ...partial })),
    addOrder: (o) => {
      const id = 'O-' + Math.floor(7800 + Math.random() * 199);
      setStore(prev => ({ ...prev, orders: [{ id, need: o.state === '待确认' || o.state === '待自提', pay: '微信支付', created: '刚刚', ...o }, ...prev.orders] }));
      return id;
    },
    updateOrder: (id, partial) => setStore(prev => ({ ...prev, orders: prev.orders.map(o => o.id === id ? { ...o, ...partial } : o) })),
  };

  const nav = {
    push: (name, props = {}) => setStack(s => [...s, { name, props }]),
    pop: () => setStack(s => s.slice(0, -1)),
    reset: (newTab) => { setStack([]); setTab(newTab); },
    depth: stack.length,
  };

  const switchTab = (k) => { setStack([]); setTab(k); };

  const ROUTES = {
    group:        (p) => <window.GroupPhotoScreen store={storeApi} nav={nav} {...p} />,
    product:      (p) => <window.WorksScreen store={storeApi} nav={nav} onBind={() => nav.push('bind')} initialTab={p.cat} sku={p.sku} focusPos={p.focusPos} focusSection={p.focusSection} openTheme={p.openTheme} openPos={p.openPos} pushed />,
    themeDetail:  (p) => <window.ThemeDetailScreen store={storeApi} nav={nav} {...p} />,
    customize:    (p) => <window.CustomizeScreen store={storeApi} nav={nav} {...p} />,
    customizeDetail:(p) => <window.CustomizeDetailScreen nav={nav} {...p} />,
    portraitManage:(p) => <window.PortraitManageScreen nav={nav} {...p} />,
    portraitList: () => <window.PortraitListScreen nav={nav} />,
    wcCustomize:  (p) => <window.WenchuangCustomizeScreen store={storeApi} nav={nav} {...p} />,
    jingxiuFlow:  (p) => <window.JingxiuFlowScreen store={storeApi} nav={nav} {...p} />,
    wenchuangFlow:(p) => <window.WenchuangFlowScreen store={storeApi} nav={nav} {...p} />,
    wenchuangDetail:(p) => <window.WenchuangDetailScreen store={storeApi} nav={nav} {...p} />,
    caseDetail:   (p) => <window.CaseDetailScreen store={storeApi} nav={nav} {...p} />,
    workPhoto:    (p) => <window.WorkPhotoScreen store={storeApi} nav={nav} {...p} />,
    gallery:      (p) => <window.GalleryScreen nav={nav} {...p} />,
    messages:     () => <window.MessagesScreen nav={nav} />,
    service:      () => <window.ServiceScreen nav={nav} />,
    bindHelp:     () => <window.BindHelpScreen nav={nav} />,
    recover:      () => <window.RecoverScreen store={storeApi} nav={nav} />,
    bind:         (p) => <window.BindScreen store={storeApi} nav={nav} {...p} />,
    bindOk:       () => <window.BindSuccessScreen store={storeApi} nav={nav} />,
    previewSample:() => <window.PreviewSampleScreen store={storeApi} nav={nav} />,
    orderDetail:  (p) => <window.OrderDetailScreen store={storeApi} nav={nav} {...p} />,
    cyLocked:     (p) => <window.CreativeLockedScreen store={storeApi} nav={nav} {...p} />,
    assetList:    (p) => <window.AssetListScreen store={storeApi} nav={nav} {...p} />,
    settings:     (p) => <window.SettingsScreen store={storeApi} nav={nav} {...p} />,
    onsite:       () => <window.OnsitePickupScreen store={storeApi} nav={nav} />,
    landing:      (p) => <window.ConvertLandingScreen store={storeApi} nav={nav} {...p} />,
  };

  const TABS = {
    home:   () => <window.HomeScreen store={storeApi} nav={nav} onBind={() => nav.push('bind')} scene={scene} />,
    works:  () => <window.WorksScreen store={storeApi} nav={nav} onBind={() => nav.push('bind')} />,
    orders: () => <window.OrdersScreen store={storeApi} nav={nav} />,
    mine:   () => <window.MineScreen store={storeApi} nav={nav} />,
  };

  const top = stack[stack.length - 1];
  const showTabBar = !top;

  let content;
  if (top) {
    content = <div key={top.name + stack.length} style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden', animation: 'lvPush .26s cubic-bezier(.2,.8,.2,1)' }}>{ROUTES[top.name] ? ROUTES[top.name](top.props) : <div style={{ padding: 40 }}>404</div>}</div>;
  } else {
    content = (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>{TABS[tab]()}</div>
        <window.TabBar active={tab} onTab={switchTab} onBind={() => nav.push('bind')} />
      </div>
    );
  }

  return (
    <Stage bg={t.stageBg}>
      <window.IOSDevice dark={top && top.name === 'bind'}>
        <div style={{ position: 'relative', height: '100%', overflow: 'hidden', background: LVT.paper }}>
          {content}
          {push && window.ServicePush &&
            <window.ServicePush scene={scene}
              onOpen={() => {setPush(false);setTab('home');setStack([{ name: 'landing', props: { sceneKey } }]);}}
              onClose={() => setPush(false)} />}
        </div>
      </window.IOSDevice>
      <TweaksPanel title="Tweaks">
        <TweakSection label="外观" />
        <TweakColor label="强调色" value={t.accent}
          options={['#1A1916', '#2F6F63', '#9A6A3C', '#2E6E8E']}
          onChange={(v) => setTweak('accent', v)} />
        <TweakColor label="舞台背景" value={t.stageBg}
          options={['#161512', '#3A4A47', '#6E6357', '#0F1518']}
          onChange={(v) => setTweak('stageBg', v)} />
        <TweakSection label="转化场景" />
        <TweakRadio label="付费引导场景" value={t.scene}
          options={['1 拍摄完 / 绑卡后', '2 取片点现场加购', '3 当晚推送', '4 一周后推送']}
          onChange={(v) => setTweak('scene', v)} />
        <TweakSection label="演示" />
        <TweakRadio label="照片流程阶段" value={t.demoStage}
          options={['未绑卡', '照片已到', '已领免费', '已购整组']}
          onChange={(v) => setTweak('demoStage', v)} />
      </TweaksPanel>
    </Stage>
  );
}

// letterbox stage that scales the 402×874 device to fit viewport
function Stage({ children, bg }) {
  const [scale, setScale] = React.useState(1);
  React.useEffect(() => {
    const fit = () => {
      const m = 24;
      setScale(Math.min((window.innerHeight - m) / 874, (window.innerWidth - m) / 402, 1.15));
    };
    fit();
    window.addEventListener('resize', fit);
    return () => window.removeEventListener('resize', fit);
  }, []);
  return (
    <div style={{ position: 'fixed', inset: 0, background: bg, display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'background .3s' }}>
      <div style={{ width: 402, height: 874, transform: `scale(${scale})`, transformOrigin: 'center', flexShrink: 0 }}>
        {children}
      </div>
    </div>
  );
}

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