// app.jsx — main wiring + state + router.

const INITIAL_STATE = {
  route: 'home',
  creator: { libraryCount: 20 },
  editor: {
    appName: 'Coupon Manager',
    tab: 'chat',
    pointMode: false,
    selectedEl: null,
    showRollback: null,
    liveVersion: 'v3',
    chat: [
      { role: 'user', content: 'Add an "archived" state for coupons. Hide them from the default list.', ts: '1h ago' },
      {
        role: 'ai', ts: '50m ago',
        content: 'Added `status: archived`, a tab filter, and a row action "Archive". Created **v3 (Live)**.',
        change: { version: 'v3', file: 'apps/coupon-manager/list.tsx', diffLines: 28, summary: 'Add archived state + filter tab' },
      },
    ],
    versions: [
      { id: 'v3', label: 'Add archived state + filter tab', ts: '50m ago', live: true, draft: false },
      { id: 'v2', label: 'Status badge → green when active', ts: 'Yesterday', live: false, draft: false },
      { id: 'v1', label: 'Initial scaffold (from Library)', ts: '3d ago', live: false, draft: false },
    ],
  },
  storefront: {
    mode: 'anon',
    chat: [],
    versions: [
      { id: 'v4', label: 'Spin to Win · default styles', ts: '2 days ago', live: true, draft: false },
    ],
    liveVersion: 'v4',
  },
  agent: {
    setupDone: true,
    leftTab: 'chats',
    chat: [],
    pendingPlan: null,
    showSetup: false,
    workflows: [
      { id: 'wf1', name: 'VIP win-back · weekly', trigger: 'Every Mon 9am', on: true },
      { id: 'wf2', name: 'Low inventory → pause Spin to Win', trigger: 'Stock < 10', on: true },
      { id: 'wf3', name: 'Daily ops Slack summary', trigger: 'Every day 8am', on: false },
    ],
  },
  draftDetail: { id: 'wishlist-drawer' },
};

function App() {
  const [state, setState] = React.useState(INITIAL_STATE);

  const navigate = (route) => setState((s) => ({ ...s, route }));

  // First-visit help banner (small floating element)
  const [showIntro, setShowIntro] = React.useState(true);

  const route = state.route;

  // editor & storefront-edit take full content area; otherwise normal Page layout
  return (
    <>
      <Frame route={route} navigate={navigate}>
        {route === 'home' && <RouteOperations navigate={navigate} state={state} />}
        {route === 'operations' && <RouteOperations navigate={navigate} state={state} />}
        {route === 'operations/coupon' && <RouteCouponApp navigate={navigate} state={state} />}
        {route === 'creator' && <RouteCreatorHome navigate={navigate} state={state} setState={setState} />}
        {route === 'creator/library' && <RouteLibrary navigate={navigate} state={state} setState={setState} />}
        {route === 'creator/new' && <RouteNewApp navigate={navigate} state={state} setState={setState} />}
        {route === 'creator/editor' && <RouteEditor navigate={navigate} state={state} setState={setState} />}
        {route === 'creator/draft' && <RouteDraftDetail navigate={navigate} state={state} setState={setState} />}
        {route === 'creator/publish' && <RoutePublish navigate={navigate} state={state} setState={setState} />}
        {route === 'creator/dashboard' && <RoutePublisherDashboard navigate={navigate} state={state} setState={setState} />}
        {route === 'marketplace' && <RouteMarketplace navigate={navigate} state={state} setState={setState} />}
        {route === 'storefront' && <RouteStorefront navigate={navigate} state={state} setState={setState} />}
        {route === 'agent' && <RouteAgent navigate={navigate} state={state} setState={setState} />}
      </Frame>

      {showIntro && <IntroToast onClose={() => setShowIntro(false)} navigate={navigate} />}
    </>
  );
}

// Creator home — small landing with My apps + entry into AI builder
function RouteCreatorHome({ navigate, state, setState }) {
  return (
    <Page>
      <PageHeader
        eyebrow="Creator"
        title="My apps"
        primary={<Btn variant="magic" icon={I.sparkle} onClick={() => navigate('creator/new')}>Create with AI</Btn>}
        secondary={<Btn icon={I.apps} onClick={() => navigate('creator/library')}>Browse library</Btn>}
      />

      <Banner tone="magic" icon={I.sparkle} dismissible>
        <b>Tip:</b> Open any app in the editor to refine via chat + point-click — like editing a doc with AI.
      </Banner>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginTop: 16 }}>
        {[
          ['Coupon Manager', 'v3 · Live', 'success', '50m ago · Add archived state', 'creator/editor'],
          ['Loyalty Hearts', 'v7 · Live', 'success', '2h ago · Tier UI polish', 'creator/editor'],
          ['Bundle Deals', 'v2 · Live', 'success', 'Yesterday · New bundle picker', 'creator/editor'],
          ['Wishlist Drawer', 'v1 · Draft', 'magic', '3d ago · Initial scaffold', 'creator/editor'],
          ['Spin to Win', 'v4 · Paused', 'warning', '5d ago · Color tweak', 'creator/editor'],
          ['Discount Stacker', 'v1 · Live', 'success', '15m ago · Pro variant', 'creator/editor'],
          ['FAQ Block', 'v3 · Live', 'success', '1d ago · Mobile fix', 'creator/editor'],
        ].map(([n, v, t, last, route]) => (
          <Card key={n} onClick={() => navigate(route)} style={{ padding: 14, cursor: 'pointer' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <div style={{
                width: 36, height: 36, borderRadius: 9,
                background: 'var(--p-color-bg-fill-magic)',
                color: 'var(--p-color-text-magic)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontWeight: 600, fontSize: 14,
              }}>{n[0]}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600 }}>{n}</div>
                <Badge tone={t} dot>{v}</Badge>
              </div>
              <I.chevronRight size={12} />
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--p-color-text-secondary)', borderTop: '1px solid var(--p-color-border-secondary)', paddingTop: 8 }}>
              {last}
            </div>
          </Card>
        ))}

        <Card onClick={() => navigate('creator/new')} style={{
          padding: 14, cursor: 'pointer',
          borderStyle: 'dashed', borderColor: 'var(--p-color-border-magic)',
          background: 'var(--p-color-bg-fill-magic)',
          color: 'var(--p-color-text-magic)',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          textAlign: 'center', minHeight: 110,
        }}>
          <I.sparkle size={20} />
          <div style={{ fontSize: 13, fontWeight: 600, marginTop: 6 }}>Build a new app with AI</div>
          <div style={{ fontSize: 11, opacity: 0.85, marginTop: 2 }}>Sidekick-style chat · ~30s to v1</div>
        </Card>
      </div>
    </Page>
  );
}

// Floating intro toast — lets user know about prototype hot spots
function IntroToast({ onClose, navigate }) {
  return (
    <div style={{
      position: 'fixed', bottom: 16, left: 16, zIndex: 2147483640,
      maxWidth: 340, background: 'var(--p-color-bg-inverse, #1a1a1a)', color: 'white',
      borderRadius: 12, padding: '14px 16px', fontFamily: 'var(--p-font-family)',
      fontSize: 13, lineHeight: 1.5, boxShadow: '0 12px 32px rgba(0,0,0,0.25)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
        <I.sparkle size={14} />
        <b>Interactive Polaris prototype</b>
        <div style={{ flex: 1 }} />
        <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'rgba(255,255,255,0.7)', cursor: 'pointer', padding: 2 }}>
          <I.close />
        </button>
      </div>
      <div style={{ fontSize: 12, opacity: 0.85, marginBottom: 10 }}>
        Try these flagship flows:
      </div>
      <div style={{ display: 'grid', gap: 4 }}>
        {[
          ['Agent Brain · chat with your shop', 'agent'],
          ['App editor · point-click + AI chat', 'creator/editor'],
          ['Marketplace · browse & publish apps', 'marketplace'],
          ['Publisher dashboard · installs & earnings', 'creator/dashboard'],
          ['Draft detail · my AI-built apps', 'creator/draft'],
          ['Storefront · admin detect + edit mode', 'storefront'],
        ].map(([l, r]) => (
          <button key={r} onClick={() => { onClose(); navigate(r); }} style={{
            background: 'rgba(255,255,255,0.08)', border: 'none', cursor: 'pointer',
            color: 'white', textAlign: 'left', padding: '7px 10px', borderRadius: 6,
            fontSize: 12.5, fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 6,
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.16)'}
          onMouseLeave={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.08)'}
          >
            <I.chevronRight size={11} /> {l}
          </button>
        ))}
      </div>
    </div>
  );
}

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