// TradingBots.jsx - interactive web replica of the Sorin desktop Trading Bots view

const TB_TABS = ['Overview', 'Assets', 'Automation', 'Audit'];

function createMockBot({ id, name }) {
  return {
    id,
    name,
    subtitle: 'Paper trading bot',
    summary:
      'React to market-moving events and high-conviction crypto price moves across major assets, acting quickly while staying inside explicit trade and daily risk limits.',
    tokens: ['BTC', 'ETH'],
    mode: 'Paper trading',
    address: 'Simulated (no real address)',
    approvalMode: 'Auto approve',
    created: '2026/5/12',
    armed: true,
    paused: false,
    maxOrderSize: '$1,000',
    dailyCap: '$10,000',
    maxSlippage: '50 bps',
    rerouteAttempts: '1',
    autoPauseAfter: '2 failures',
    lastExecution: 'Bot must be armed before autonomous trading. Current state: ready.',
    assets: [
      { symbol: 'BTC', route: 'On-chain (DEX)', allocation: '55%', balance: '0.1821', pnl: '+4.8%' },
      { symbol: 'ETH', route: 'CEX', allocation: '45%', balance: '2.46', pnl: '+2.1%' },
    ],
    schedules: [
      { id: 'event-scan', name: 'Event catalyst scan', cadence: 'Every 15m', nextRun: 'In 6m', active: true },
    ],
    audit: [
      { id: 'a1', kind: 'Policy', message: 'Risk envelope loaded from mock policy', time: '10:42' },
      { id: 'a2', kind: 'System', message: 'Paper session initialized locally', time: '10:44' },
      { id: 'a3', kind: 'Order', message: 'No live orders submitted', time: '10:45' },
    ],
    routes: [
      { name: 'On-chain (DEX)', status: 'Healthy' },
      { name: 'CEX', status: 'Healthy' },
    ],
  };
}

function initialTradingBots() {
  return [createMockBot({ id: 'paper-event', name: 'Paper Event Bot' })];
}

function createAudit(kind, message) {
  const now = new Date();
  return {
    id: `${kind}-${now.getTime()}`,
    kind,
    message,
    time: `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`,
  };
}

function useTradingViewport() {
  const [width, setWidth] = React.useState(() => (typeof window === 'undefined' ? 1440 : window.innerWidth));

  React.useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return {
    isDense: width < 1500,
    isCompact: width < 1180,
    isPhone: width < 700,
  };
}

function SorinMark({ width = 108, opacity = 0.42 }) {
  return <img src="assets/logo-mark.svg" alt="" style={{ width, opacity, display: 'block', filter: 'invert(1)' }} />;
}

function NativeTopBar() {
  return (
    <header style={tbStyles.topBar}>
      <div style={tbStyles.topBrand}>
        <SorinMark width={46} opacity={0.32} />
        <span style={tbStyles.topDot} />
        <span style={tbStyles.topName}>Sorin</span>
      </div>
      <div style={tbStyles.windowControls} aria-label="Window controls">
        <span style={tbStyles.windowControl}>x</span>
        <span style={tbStyles.windowControl}>-</span>
        <span style={tbStyles.windowBox} />
      </div>
    </header>
  );
}

function TradingNavItem({ icon, label, active = false, chevron = false }) {
  return (
    <button type="button" style={{ ...tbStyles.navItem, ...(active ? tbStyles.navItemActive : {}) }}>
      {active && <span style={tbStyles.activeRail} />}
      <i className={icon} style={{ ...tbStyles.navIcon, ...(active ? tbStyles.navIconActive : {}) }} />
      <span>{label}</span>
      {chevron && <i className="ri-arrow-down-s-line" style={tbStyles.navChevron} />}
    </button>
  );
}

function TradingBotsSidebar({ bots, selectedId, onSelectBot }) {
  const items = [
    { icon: 'ri-add-line', label: 'New Task' },
    { icon: 'ri-bar-chart-box-line', label: 'Portfolio' },
    { icon: 'ri-robot-2-line', label: 'Trading Bots', active: true, chevron: true },
    { icon: 'ri-time-line', label: 'Automation', chevron: true },
    { icon: 'ri-broadcast-line', label: 'Data Feeds' },
    { icon: 'ri-equalizer-line', label: 'Customize', chevron: true },
  ];

  return (
    <aside style={tbStyles.sidebar}>
      <div style={tbStyles.sidebarInner}>
        <div style={tbStyles.sidebarHeader}>
          <SorinMark />
          <span style={tbStyles.sidebarBrand}>Sorin</span>
          <span style={tbStyles.betaPill}>Beta</span>
        </div>

        <nav style={tbStyles.navList} aria-label="Sorin desktop navigation">
          {items.map((item) => (
            <div key={item.label}>
              <TradingNavItem {...item} />
              {item.active && (
                <div style={tbStyles.childStack}>
                  {bots.map((bot) => (
                    <button
                      key={bot.id}
                      type="button"
                      style={{ ...tbStyles.childNav, ...(bot.id === selectedId ? tbStyles.childNavActive : {}) }}
                      onClick={() => onSelectBot(bot.id)}
                    >
                      <i className="ri-robot-2-line" />
                      <span>{bot.name}</span>
                    </button>
                  ))}
                </div>
              )}
            </div>
          ))}
        </nav>

        <section style={tbStyles.recentsPanel}>
          <h2 style={tbStyles.recentsTitle}>Recents</h2>
          <p style={tbStyles.recentsSub}>3 conversations</p>
          <div style={tbStyles.recentList}>
            {['ETH Swing Setup', 'BTC DCA Automation', 'Narrative Rotation Radar'].map((item) => (
              <button key={item} type="button" style={tbStyles.recentItem}>
                <span style={tbStyles.recentDot} />
                {item}
              </button>
            ))}
          </div>
        </section>

        <div style={tbStyles.walletBox}>
          <span style={tbStyles.walletAvatar} />
          <span style={tbStyles.walletText}>0x43d4...4ae5</span>
          <i className="ri-arrow-down-s-fill" style={tbStyles.walletChevron} />
        </div>
      </div>
    </aside>
  );
}

function StatusBadge({ children, tone = 'neutral' }) {
  const style =
    tone === 'paper'
      ? tbStyles.paperBadge
      : tone === 'paused'
        ? tbStyles.pausedBadge
        : tone === 'disarmed'
          ? tbStyles.disarmedBadge
          : tbStyles.armedBadge;
  return <span style={{ ...tbStyles.badgeBase, ...style }}>{children}</span>;
}

function IconButton({ icon, label, onClick }) {
  return (
    <button type="button" aria-label={label} title={label} style={tbStyles.iconButton} onClick={onClick}>
      <i className={icon} />
    </button>
  );
}

function HeaderPanel({ onBack, botCount, onCreateBot, onQuickAction, dense = false, compact = false }) {
  return (
    <section style={{ ...tbStyles.headerPanel, ...(dense ? tbStyles.headerPanelDense : {}), ...(compact ? tbStyles.headerPanelCompact : {}) }}>
      <div>
        <div style={{ ...tbStyles.headerTitleRow, ...(compact ? tbStyles.headerTitleRowCompact : {}) }}>
          {onBack && (
            <button type="button" aria-label="Back to campaign" style={tbStyles.backButton} onClick={onBack}>
              <i className="ri-arrow-left-line" />
              Campaign
            </button>
          )}
          <div style={tbStyles.headerPill}>TRADING BOTS</div>
        </div>
        <p style={{ ...tbStyles.headerCopy, ...(dense ? tbStyles.headerCopyDense : {}) }}>Create and manage bots that Sorin can use to execute trades on your behalf.</p>
      </div>
      <div style={{ ...tbStyles.headerActions, ...(compact ? tbStyles.headerActionsCompact : {}) }}>
        <p style={tbStyles.botCount}>
          {botCount} <span style={tbStyles.botCountLabel}>{botCount === 1 ? 'bot' : 'bots'}</span>
        </p>
        <div style={tbStyles.headerIconRow}>
          <IconButton icon="ri-flashlight-line" label="Quick actions" onClick={onQuickAction} />
          <IconButton icon="ri-add-line" label="Create bot" onClick={onCreateBot} />
        </div>
      </div>
    </section>
  );
}

function BotListPanel({ bots, selectedId, onSelectBot, compact = false }) {
  return (
    <section style={{ ...tbStyles.botListPanel, ...(compact ? tbStyles.botListPanelCompact : {}) }}>
      <div style={tbStyles.botListStack}>
        {bots.map((bot) => (
          <button
            key={bot.id}
            type="button"
            aria-label={`Open ${bot.name}`}
            style={{ ...tbStyles.botCard, ...(compact ? tbStyles.botCardCompact : {}), ...(bot.id === selectedId ? tbStyles.botCardActive : {}) }}
            onClick={() => onSelectBot(bot.id)}
          >
            <div style={tbStyles.botCardHeader}>
              <strong style={tbStyles.botCardTitle}>{bot.name}</strong>
              <div style={tbStyles.badgeRow}>
                <StatusBadge tone="paper">Paper</StatusBadge>
                <StatusBadge tone={bot.armed ? (bot.paused ? 'paused' : 'neutral') : 'disarmed'}>
                  {bot.armed ? (bot.paused ? 'Paused' : 'Armed') : 'Disarmed'}
                </StatusBadge>
              </div>
            </div>
            <p style={tbStyles.botCardCopy}>{bot.summary.slice(0, 108)}...</p>
            <p style={tbStyles.botCardMeta}>
              {bot.tokens.map((token) => `${token}/USDT`).join(', ')} <span>{bot.schedules.length} schedule</span>
            </p>
          </button>
        ))}
      </div>
    </section>
  );
}

function DetailTabs({ activeTab, onChange }) {
  const icons = {
    Overview: 'ri-dashboard-line',
    Assets: 'ri-link-m',
    Automation: 'ri-file-list-3-line',
    Audit: 'ri-clipboard-line',
  };
  return (
    <div style={tbStyles.tabs}>
      {TB_TABS.map((label) => (
        <button
          key={label}
          type="button"
          style={{ ...tbStyles.tab, ...(activeTab === label ? tbStyles.tabActive : {}) }}
          onClick={() => onChange(label)}
        >
          <i className={icons[label]} />
          {label}
        </button>
      ))}
    </div>
  );
}

function DetailRow({ label, value }) {
  return (
    <div style={tbStyles.detailRow}>
      <span style={tbStyles.detailLabel}>{label}</span>
      <strong style={tbStyles.detailValue}>{value}</strong>
    </div>
  );
}

function InfoCard({ icon, title, children, tall = false, compact = false }) {
  return (
    <section style={{ ...tbStyles.infoCard, ...(tall && !compact ? tbStyles.infoCardTall : {}), ...(compact ? tbStyles.infoCardCompact : {}) }}>
      <h3 style={tbStyles.infoTitle}>
        <i className={icon} />
        {title}
      </h3>
      {children}
    </section>
  );
}

function OverviewTab({ bot, compact = false }) {
  return (
    <div style={{ ...tbStyles.infoGrid, ...(compact ? tbStyles.infoGridCompact : {}) }}>
      <InfoCard icon="ri-wallet-3-line" title="Identity & Mandate" tall compact={compact}>
        <p style={tbStyles.mandateText}>{bot.summary}</p>
        <div style={tbStyles.divider} />
        <div style={tbStyles.rowStack}>
          <DetailRow label="Mode" value={bot.mode} />
          <DetailRow label="Address" value={bot.address} />
          <DetailRow label="Approval mode" value={bot.approvalMode} />
          <DetailRow label="Created" value={bot.created} />
        </div>
      </InfoCard>

      <InfoCard icon="ri-shield-line" title="Trading Policy" tall compact={compact}>
        <div style={{ ...tbStyles.rowStack, marginTop: 23 }}>
          <DetailRow label="Allowed tokens" value={bot.tokens.join(', ')} />
          <DetailRow label="Max order size" value={bot.maxOrderSize} />
          <DetailRow label="Daily notional cap" value={bot.dailyCap} />
          <DetailRow label="Max slippage" value={bot.maxSlippage} />
          <DetailRow label="Reroute attempts" value={bot.rerouteAttempts} />
          <DetailRow label="Auto-pause after" value={bot.autoPauseAfter} />
        </div>
        <div style={tbStyles.executionNotice}>
          <p style={tbStyles.executionNoticeTitle}>Last execution</p>
          <span style={tbStyles.executionNoticeCopy}>{bot.lastExecution}</span>
        </div>
      </InfoCard>

      <InfoCard icon="ri-key-2-line" title="Custody & Security" compact={compact}>
        <div style={{ ...tbStyles.rowStack, marginTop: 25 }}>
          <DetailRow label="Custody type" value="None (paper trading)" />
          <DetailRow label="Session status" value={bot.paused ? 'Paused locally' : 'Simulated'} />
        </div>
      </InfoCard>

      <InfoCard icon="ri-external-link-line" title="Execution Routes" compact={compact}>
        <div style={tbStyles.routeStack}>
          {bot.routes.map((route) => (
            <div key={route.name} style={tbStyles.routeRow}>
              <span>{route.name}</span>
              <strong style={tbStyles.routeStatus}>{route.status}</strong>
            </div>
          ))}
        </div>
      </InfoCard>
    </div>
  );
}

function AssetsTab({ bot, onAddAsset, onRebalance, compact = false }) {
  return (
    <div style={{ ...tbStyles.tabContentGrid, ...(compact ? tbStyles.tabContentGridCompact : {}) }}>
      <InfoCard icon="ri-wallet-line" title="Mock balances" compact={compact}>
        <div style={tbStyles.assetStack}>
          {bot.assets.map((asset) => (
            <div key={asset.symbol} style={{ ...tbStyles.assetRow, ...(compact ? tbStyles.assetRowCompact : {}) }}>
              <div>
                <strong style={tbStyles.assetSymbol}>{asset.symbol}</strong>
                <span style={tbStyles.assetRoute}>{asset.route}</span>
              </div>
              <DetailRow label="Allocation" value={asset.allocation} />
              <DetailRow label="Balance" value={asset.balance} />
              <DetailRow label="PNL" value={asset.pnl} />
            </div>
          ))}
        </div>
      </InfoCard>
      <InfoCard icon="ri-funds-line" title="Asset controls" compact={compact}>
        <p style={tbStyles.panelCopy}>Everything here is local mock data. Rebalance changes the audit trail only.</p>
        <div style={tbStyles.actionRow}>
          <button type="button" style={tbStyles.actionButton} onClick={onAddAsset}>
            Add asset
          </button>
          <button type="button" style={tbStyles.actionButton} onClick={onRebalance}>
            Simulate rebalance
          </button>
        </div>
      </InfoCard>
    </div>
  );
}

function AutomationTab({ bot, onToggleSchedule, onDryRun, onCreateSchedule, compact = false }) {
  return (
    <div style={{ ...tbStyles.tabContentGrid, ...(compact ? tbStyles.tabContentGridCompact : {}) }}>
      <InfoCard icon="ri-calendar-check-line" title="Schedules" compact={compact}>
        <div style={tbStyles.routeStack}>
          {bot.schedules.map((schedule) => (
            <div key={schedule.id} style={tbStyles.scheduleRow}>
              <div>
                <strong style={tbStyles.scheduleTitle}>{schedule.name}</strong>
                <span style={tbStyles.scheduleMeta}>
                  {schedule.cadence} · {schedule.nextRun}
                </span>
              </div>
              <button type="button" style={tbStyles.smallButton} onClick={() => onToggleSchedule(schedule.id)}>
                {schedule.active ? 'Pause schedule' : 'Resume schedule'}
              </button>
            </div>
          ))}
        </div>
      </InfoCard>
      <InfoCard icon="ri-flashlight-line" title="Automation actions" compact={compact}>
        <p style={tbStyles.panelCopy}>Dry runs, schedule creation, and policy checks stay in browser state.</p>
        <div style={tbStyles.actionRow}>
          <button type="button" style={tbStyles.actionButton} onClick={onDryRun}>
            Run dry run
          </button>
          <button type="button" style={tbStyles.actionButton} onClick={onCreateSchedule}>
            Create schedule
          </button>
        </div>
      </InfoCard>
    </div>
  );
}

function AuditTab({ bot, auditFilter, onFilter, onExport, compact = false }) {
  const logs = auditFilter === 'All' ? bot.audit : bot.audit.filter((item) => item.kind === auditFilter);
  return (
    <div style={tbStyles.auditLayout}>
      <div style={tbStyles.auditToolbar}>
        {['All', 'Order', 'Policy', 'System'].map((filter) => (
          <button
            key={filter}
            type="button"
            style={{ ...tbStyles.filterButton, ...(auditFilter === filter ? tbStyles.filterButtonActive : {}) }}
            onClick={() => onFilter(filter)}
          >
            {filter}
          </button>
        ))}
        <button type="button" style={tbStyles.actionButton} onClick={onExport}>
          Export audit
        </button>
      </div>
      <div style={tbStyles.auditList}>
        {logs.map((item) => (
          <div key={item.id} style={{ ...tbStyles.auditRow, ...(compact ? tbStyles.auditRowCompact : {}) }}>
            <span style={tbStyles.auditKind}>{item.kind}</span>
            <strong style={tbStyles.auditMessage}>{item.message}</strong>
            <span style={tbStyles.auditTime}>{item.time}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function BotDetailPanel({
  bot,
  activeTab,
  auditFilter,
  onTabChange,
  onTogglePause,
  onToggleArmed,
  onOpenChat,
  onEditBot,
  onDeleteBot,
  onClearBot,
  onAddAsset,
  onRebalance,
  onToggleSchedule,
  onDryRun,
  onCreateSchedule,
  onAuditFilter,
  onExportAudit,
  compact = false,
  dense = false,
}) {
  return (
    <section style={{ ...tbStyles.detailPanel, ...(dense ? tbStyles.detailPanelDense : {}), ...(compact ? tbStyles.detailPanelCompact : {}) }} aria-label="Bot details">
      <div style={{ ...tbStyles.detailTop, ...(compact ? tbStyles.detailTopCompact : {}) }}>
        <div>
          <div style={tbStyles.detailTitleRow}>
            <h1 style={tbStyles.detailTitle}>{bot.name}</h1>
            <StatusBadge tone="paper">Paper</StatusBadge>
            <StatusBadge tone={bot.armed ? (bot.paused ? 'paused' : 'neutral') : 'disarmed'}>
              {bot.armed ? (bot.paused ? 'Paused' : 'Armed') : 'Disarmed'}
            </StatusBadge>
          </div>
          <p style={tbStyles.detailSubtitle}>{bot.subtitle}</p>
        </div>
        <div style={{ ...tbStyles.detailActions, ...(compact ? tbStyles.detailActionsCompact : {}) }}>
          <button type="button" style={tbStyles.pauseButton} onClick={onTogglePause}>
            {bot.paused ? 'Resume bot' : 'Pause bot'}
          </button>
          <button type="button" style={tbStyles.pauseButton} onClick={onToggleArmed}>
            {bot.armed ? 'Disarm bot' : 'Arm bot'}
          </button>
          <IconButton icon="ri-message-2-line" label="Open bot chat" onClick={onOpenChat} />
          <IconButton icon="ri-pencil-line" label="Edit bot" onClick={onEditBot} />
          <IconButton icon="ri-delete-bin-line" label="Delete bot" onClick={onDeleteBot} />
          <IconButton icon="ri-eraser-line" label="Clear bot" onClick={onClearBot} />
        </div>
      </div>

      <DetailTabs activeTab={activeTab} onChange={onTabChange} />

      {activeTab === 'Overview' && <OverviewTab bot={bot} compact={compact} />}
      {activeTab === 'Assets' && <AssetsTab bot={bot} onAddAsset={onAddAsset} onRebalance={onRebalance} compact={compact} />}
      {activeTab === 'Automation' && (
        <AutomationTab
          bot={bot}
          onToggleSchedule={onToggleSchedule}
          onDryRun={onDryRun}
          onCreateSchedule={onCreateSchedule}
          compact={compact}
        />
      )}
      {activeTab === 'Audit' && (
        <AuditTab bot={bot} auditFilter={auditFilter} onFilter={onAuditFilter} onExport={onExportAudit} compact={compact} />
      )}
    </section>
  );
}

function Toast({ text }) {
  if (!text) return null;
  return (
    <div role="status" style={tbStyles.toast}>
      <i className="ri-checkbox-circle-line" />
      {text}
    </div>
  );
}

function BotFormModal({ mode, bot, onClose, onSave }) {
  const isCreate = mode === 'create';
  const [name, setName] = React.useState(isCreate ? '' : bot.name);
  const [summary, setSummary] = React.useState(isCreate ? 'Trade high-conviction crypto moves with mock execution.' : bot.summary);

  return (
    <div style={tbStyles.modalBackdrop}>
      <section role="dialog" aria-label={isCreate ? 'Create bot' : 'Edit bot'} style={tbStyles.modal}>
        <div style={tbStyles.modalHeader}>
          <h2 style={tbStyles.modalTitle}>{isCreate ? 'Create bot' : 'Edit bot'}</h2>
          <IconButton icon="ri-close-line" label="Close modal" onClick={onClose} />
        </div>
        <label style={tbStyles.fieldLabel}>
          {isCreate ? 'New bot name' : 'Bot name'}
          <input
            aria-label={isCreate ? 'New bot name' : 'Bot name'}
            style={tbStyles.fieldInput}
            value={name}
            onChange={(event) => setName(event.target.value)}
          />
        </label>
        <label style={tbStyles.fieldLabel}>
          Mandate
          <textarea
            aria-label="Mandate"
            style={{ ...tbStyles.fieldInput, ...tbStyles.fieldTextArea }}
            value={summary}
            onChange={(event) => setSummary(event.target.value)}
          />
        </label>
        <div style={tbStyles.modalActions}>
          <button type="button" style={tbStyles.secondaryButton} onClick={onClose}>
            Cancel
          </button>
          <button
            type="button"
            style={tbStyles.primaryButton}
            onClick={() => onSave({ name: name.trim() || (isCreate ? 'Untitled Paper Bot' : bot.name), summary })}
          >
            {isCreate ? 'Save bot' : 'Save changes'}
          </button>
        </div>
      </section>
    </div>
  );
}

function AddAssetModal({ onClose, onAdd }) {
  return (
    <div style={tbStyles.modalBackdrop}>
      <section role="dialog" aria-label="Add asset" style={tbStyles.modal}>
        <div style={tbStyles.modalHeader}>
          <h2 style={tbStyles.modalTitle}>Add asset</h2>
          <IconButton icon="ri-close-line" label="Close modal" onClick={onClose} />
        </div>
        <p style={tbStyles.panelCopy}>Pick a mocked asset. The bot policy and balances update locally.</p>
        <div style={tbStyles.templateGrid}>
          {['SOL', 'LINK', 'DOGE'].map((symbol) => (
            <button key={symbol} type="button" style={tbStyles.templateButton} onClick={() => onAdd(symbol)}>
              Add {symbol}
            </button>
          ))}
        </div>
      </section>
    </div>
  );
}

function ScheduleModal({ onClose, onCreate }) {
  return (
    <div style={tbStyles.modalBackdrop}>
      <section role="dialog" aria-label="Create schedule" style={tbStyles.modal}>
        <div style={tbStyles.modalHeader}>
          <h2 style={tbStyles.modalTitle}>Create schedule</h2>
          <IconButton icon="ri-close-line" label="Close modal" onClick={onClose} />
        </div>
        <p style={tbStyles.panelCopy}>Mock schedules run only in this preview state.</p>
        <button type="button" style={tbStyles.primaryButton} onClick={onCreate}>
          Add daily check
        </button>
      </section>
    </div>
  );
}

function DeleteModal({ bot, onClose, onConfirm }) {
  return (
    <div style={tbStyles.modalBackdrop}>
      <section role="dialog" aria-label="Delete bot" style={tbStyles.modal}>
        <div style={tbStyles.modalHeader}>
          <h2 style={tbStyles.modalTitle}>Delete bot</h2>
          <IconButton icon="ri-close-line" label="Close modal" onClick={onClose} />
        </div>
        <p style={tbStyles.panelCopy}>This removes {bot.name} from the local mock list only.</p>
        <div style={tbStyles.modalActions}>
          <button type="button" style={tbStyles.secondaryButton} onClick={onClose}>
            Cancel
          </button>
          <button type="button" style={tbStyles.dangerButton} onClick={onConfirm}>
            Confirm delete
          </button>
        </div>
      </section>
    </div>
  );
}

function ChatDrawer({ bot, onClose, compact = false }) {
  const [input, setInput] = React.useState('');
  const [messages, setMessages] = React.useState([
    { from: 'bot', text: `${bot.name} is running in paper mode. Ask about policy, assets, or execution routes.` },
  ]);

  const sendMessage = () => {
    if (!input.trim()) return;
    setMessages((current) => [
      ...current,
      { from: 'user', text: input.trim() },
      { from: 'bot', text: 'Mock response queued: I would check event confidence, cap exposure, then route through the healthiest venue.' },
    ]);
    setInput('');
  };

  return (
    <aside role="dialog" aria-label="Bot chat" style={{ ...tbStyles.chatDrawer, ...(compact ? tbStyles.chatDrawerCompact : {}) }}>
      <div style={tbStyles.modalHeader}>
        <h2 style={tbStyles.modalTitle}>Bot chat</h2>
        <IconButton icon="ri-close-line" label="Close chat" onClick={onClose} />
      </div>
      <div style={tbStyles.chatLog}>
        {messages.map((message, index) => (
          <p
            key={`${message.from}-${index}`}
            style={{ ...tbStyles.chatBubble, ...(message.from === 'user' ? tbStyles.chatBubbleUser : {}) }}
          >
            {message.text}
          </p>
        ))}
      </div>
      <div style={tbStyles.chatComposer}>
        <input
          placeholder="Ask this bot"
          style={tbStyles.chatInput}
          value={input}
          onChange={(event) => setInput(event.target.value)}
        />
        <button type="button" aria-label="Send message" style={tbStyles.primaryIconButton} onClick={sendMessage}>
          <i className="ri-send-plane-2-line" />
        </button>
      </div>
    </aside>
  );
}

function QuickActionMenu({ onRunCheck, onSeedBot, onSimulateFill }) {
  return (
    <div style={tbStyles.quickMenu}>
      <button type="button" style={tbStyles.quickMenuItem} onClick={onRunCheck}>
        Run health check
      </button>
      <button type="button" style={tbStyles.quickMenuItem} onClick={onSeedBot}>
        Seed mock bot
      </button>
      <button type="button" style={tbStyles.quickMenuItem} onClick={onSimulateFill}>
        Simulate fill
      </button>
    </div>
  );
}

function TradingBotsDesktop({ onBack }) {
  const viewport = useTradingViewport();
  const [bots, setBots] = React.useState(initialTradingBots);
  const [selectedId, setSelectedId] = React.useState('paper-event');
  const [activeTab, setActiveTab] = React.useState('Overview');
  const [auditFilter, setAuditFilter] = React.useState('All');
  const [toast, setToast] = React.useState('');
  const [modal, setModal] = React.useState(null);
  const [chatOpen, setChatOpen] = React.useState(false);
  const [quickOpen, setQuickOpen] = React.useState(false);

  const selectedBot = bots.find((bot) => bot.id === selectedId) || bots[0];

  const showToast = (message) => setToast(message);
  const updateSelectedBot = (updater) => {
    setBots((current) => current.map((bot) => (bot.id === selectedBot.id ? updater(bot) : bot)));
  };
  const addAudit = (kind, message) => {
    updateSelectedBot((bot) => ({ ...bot, audit: [createAudit(kind, message), ...bot.audit].slice(0, 8) }));
  };

  const createBot = ({ name, summary }) => {
    const id = `mock-${Date.now()}`;
    const nextBot = {
      ...createMockBot({ id, name }),
      summary,
      tokens: ['BTC'],
      assets: [{ symbol: 'BTC', route: 'On-chain (DEX)', allocation: '100%', balance: '0.043', pnl: '+0.0%' }],
      schedules: [{ id: `${id}-schedule`, name: 'Daily momentum check', cadence: 'Daily', nextRun: 'Tomorrow', active: true }],
    };
    setBots((current) => [...current, nextBot]);
    setSelectedId(id);
    setActiveTab('Overview');
    setModal(null);
    showToast('Mock bot created');
  };

  const editBot = ({ name, summary }) => {
    updateSelectedBot((bot) => ({
      ...bot,
      name,
      summary,
      audit: [createAudit('Policy', 'Mandate edited locally'), ...bot.audit].slice(0, 8),
    }));
    setModal(null);
    showToast('Bot settings saved');
  };

  const deleteSelectedBot = () => {
    setBots((current) => {
      const nextBots = current.filter((bot) => bot.id !== selectedBot.id);
      const safeBots = nextBots.length ? nextBots : initialTradingBots();
      setSelectedId(safeBots[0].id);
      setActiveTab('Overview');
      return safeBots;
    });
    setModal(null);
    showToast('Bot deleted');
  };

  const addAsset = (symbol) => {
    updateSelectedBot((bot) => {
      if (bot.assets.some((asset) => asset.symbol === symbol)) return bot;
      return {
        ...bot,
        tokens: Array.from(new Set([...bot.tokens, symbol])),
        assets: [
          ...bot.assets,
          { symbol, route: symbol === 'SOL' ? 'On-chain (DEX)' : 'CEX', allocation: '10%', balance: '0.00', pnl: '+0.0%' },
        ],
        audit: [createAudit('Policy', `${symbol} added to mock asset universe`), ...bot.audit].slice(0, 8),
      };
    });
    setModal(null);
    setActiveTab('Assets');
    showToast(`${symbol} mock asset added`);
  };

  const toggleSchedule = (scheduleId) => {
    const wasActive = Boolean(selectedBot.schedules.find((schedule) => schedule.id === scheduleId)?.active);
    updateSelectedBot((bot) => ({
      ...bot,
      schedules: bot.schedules.map((schedule) => {
        if (schedule.id !== scheduleId) return schedule;
        return { ...schedule, active: !schedule.active };
      }),
      audit: [createAudit('System', wasActive ? 'Schedule paused' : 'Schedule resumed'), ...bot.audit].slice(0, 8),
    }));
    showToast(wasActive ? 'Schedule paused' : 'Schedule resumed');
  };

  const runDryRun = () => {
    updateSelectedBot((bot) => ({
      ...bot,
      lastExecution: 'Dry run completed with no live orders. Mock routes stayed healthy.',
      audit: [createAudit('Order', 'Dry run completed without submitting an order'), ...bot.audit].slice(0, 8),
    }));
    showToast('Dry run completed');
  };

  const createSchedule = () => {
    updateSelectedBot((bot) => ({
      ...bot,
      schedules: [
        ...bot.schedules,
        { id: `schedule-${Date.now()}`, name: 'Daily risk check', cadence: 'Daily', nextRun: 'Tomorrow', active: true },
      ],
      audit: [createAudit('System', 'Daily risk check schedule created'), ...bot.audit].slice(0, 8),
    }));
    setModal(null);
    setActiveTab('Automation');
    showToast('Schedule created');
  };

  const seedMockBot = () => createBot({ name: `Mock Momentum Bot ${bots.length + 1}`, summary: 'Mock seeded bot for frontend demo flow.' });

  return (
    <div style={tbStyles.root} data-view="trading-bots">
      <NativeTopBar />
      <div style={tbStyles.workspace}>
        <main
          style={{
            ...tbStyles.main,
            ...(viewport.isDense ? tbStyles.mainDense : {}),
            ...(viewport.isCompact ? tbStyles.mainCompact : {}),
            ...(viewport.isPhone ? tbStyles.mainPhone : {}),
          }}
        >
          <HeaderPanel
            onBack={onBack}
            botCount={bots.length}
            onCreateBot={() => setModal('create')}
            onQuickAction={() => setQuickOpen((value) => !value)}
            dense={viewport.isDense}
            compact={viewport.isCompact}
          />
          {quickOpen && (
            <QuickActionMenu
              onRunCheck={() => {
                setQuickOpen(false);
                addAudit('System', 'Health check passed in mock mode');
                showToast('Health check passed');
              }}
              onSeedBot={() => {
                setQuickOpen(false);
                seedMockBot();
              }}
              onSimulateFill={() => {
                setQuickOpen(false);
                updateSelectedBot((bot) => ({
                  ...bot,
                  lastExecution: 'Mock fill simulated at best available paper route.',
                  audit: [createAudit('Order', 'Mock fill simulated'), ...bot.audit].slice(0, 8),
                }));
                showToast('Mock fill simulated');
              }}
            />
          )}
          <div style={{ ...tbStyles.mainGrid, ...(viewport.isDense ? tbStyles.mainGridDense : {}), ...(viewport.isCompact ? tbStyles.mainGridCompact : {}) }}>
            <BotListPanel bots={bots} selectedId={selectedId} onSelectBot={setSelectedId} compact={viewport.isCompact} />
            <BotDetailPanel
              bot={selectedBot}
              activeTab={activeTab}
              auditFilter={auditFilter}
              onTabChange={setActiveTab}
              onTogglePause={() => {
                updateSelectedBot((bot) => ({
                  ...bot,
                  paused: !bot.paused,
                  audit: [createAudit('System', bot.paused ? 'Bot resumed' : 'Bot paused'), ...bot.audit].slice(0, 8),
                }));
                showToast(selectedBot.paused ? 'Bot resumed' : 'Bot paused');
              }}
              onToggleArmed={() => {
                updateSelectedBot((bot) => ({
                  ...bot,
                  armed: !bot.armed,
                  audit: [createAudit('Policy', bot.armed ? 'Bot disarmed' : 'Bot armed'), ...bot.audit].slice(0, 8),
                }));
                showToast(selectedBot.armed ? 'Bot disarmed' : 'Bot armed');
              }}
              onOpenChat={() => setChatOpen(true)}
              onEditBot={() => setModal('edit')}
              onDeleteBot={() => setModal('delete')}
              onClearBot={() => {
                updateSelectedBot((bot) => ({
                  ...bot,
                  lastExecution: 'Execution state reset. Mock queues are empty.',
                  audit: [createAudit('System', 'Execution state reset'), ...bot.audit].slice(0, 8),
                }));
                showToast('Execution state reset');
              }}
              onAddAsset={() => setModal('asset')}
              onRebalance={() => {
                addAudit('Order', 'Mock rebalance simulated');
                showToast('Mock rebalance simulated');
              }}
              onToggleSchedule={toggleSchedule}
              onDryRun={runDryRun}
              onCreateSchedule={() => setModal('schedule')}
              onAuditFilter={setAuditFilter}
              onExportAudit={() => showToast('Audit export mocked')}
              dense={viewport.isDense}
              compact={viewport.isCompact}
            />
          </div>
        </main>
      </div>
      <Toast text={toast} />
      {modal === 'create' && <BotFormModal mode="create" onClose={() => setModal(null)} onSave={createBot} />}
      {modal === 'edit' && <BotFormModal mode="edit" bot={selectedBot} onClose={() => setModal(null)} onSave={editBot} />}
      {modal === 'asset' && <AddAssetModal onClose={() => setModal(null)} onAdd={addAsset} />}
      {modal === 'schedule' && <ScheduleModal onClose={() => setModal(null)} onCreate={createSchedule} />}
      {modal === 'delete' && <DeleteModal bot={selectedBot} onClose={() => setModal(null)} onConfirm={deleteSelectedBot} />}
      {chatOpen && <ChatDrawer bot={selectedBot} onClose={() => setChatOpen(false)} compact={viewport.isPhone} />}
    </div>
  );
}

const tbStyles = {
  root: {
    width: '100vw',
    height: '100vh',
    background: 'var(--c-bg)',
    color: 'var(--c-fg)',
    fontFamily: 'var(--font-sans)',
    overflow: 'hidden',
  },
  topBar: {
    height: 58,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '0 23px',
    borderBottom: '1px solid rgba(30,30,31,0.68)',
    background: '#030303',
  },
  topBrand: { display: 'flex', alignItems: 'center', gap: 10 },
  topDot: { width: 9, height: 9, borderRadius: '50%', background: 'var(--sorin-green-bright)' },
  topName: { color: 'var(--c-fg-muted-2)', fontSize: 18, lineHeight: '24px', fontWeight: 700 },
  windowControls: {
    height: 34,
    minWidth: 128,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-around',
    border: '1px solid rgba(30,30,31,0.72)',
    borderRadius: 10,
    color: '#5E5F6A',
    fontSize: 20,
  },
  windowControl: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 24 },
  windowBox: { width: 13, height: 13, border: '2px solid currentColor', borderRadius: 2 },
  workspace: { height: 'calc(100vh - 58px)', display: 'flex', minHeight: 0 },
  sidebar: {
    width: 422,
    flex: '0 0 422px',
    padding: '10px 0 0',
  },
  sidebarInner: {
    boxSizing: 'border-box',
    height: 'calc(100% - 10px)',
    display: 'flex',
    flexDirection: 'column',
    padding: '16px 15px 18px',
    border: '1px solid var(--c-line-faint)',
    borderLeft: 0,
    borderRadius: '0 24px 24px 0',
    background: 'linear-gradient(180deg, rgba(17,17,18,0.98), rgba(8,8,8,0.98))',
  },
  sidebarHeader: {
    height: 72,
    display: 'flex',
    alignItems: 'center',
    gap: 16,
    padding: '0 10px 18px',
    borderBottom: '1px solid rgba(32,202,139,0.2)',
  },
  sidebarBrand: { color: 'var(--sorin-green)', fontSize: 30, lineHeight: '32px', fontWeight: 500 },
  betaPill: {
    display: 'inline-flex',
    alignItems: 'center',
    height: 25,
    padding: '0 9px',
    border: '1px solid rgba(32,202,139,0.45)',
    borderRadius: 8,
    color: 'var(--sorin-green)',
    background: 'rgba(32,202,139,0.12)',
    fontSize: 14,
    fontWeight: 700,
  },
  navList: { display: 'flex', flexDirection: 'column', gap: 8, marginTop: 18 },
  navItem: {
    position: 'relative',
    width: '100%',
    height: 54,
    display: 'flex',
    alignItems: 'center',
    gap: 17,
    padding: '0 17px',
    border: 0,
    borderRadius: 16,
    background: 'transparent',
    color: 'var(--c-fg-muted-2)',
    fontFamily: 'var(--font-sans)',
    fontSize: 24,
    lineHeight: '28px',
    fontWeight: 500,
    textAlign: 'left',
    cursor: 'default',
  },
  navItemActive: { color: 'var(--c-fg-muted-2)', background: 'rgba(32,202,139,0.10)' },
  activeRail: {
    position: 'absolute',
    left: 0,
    top: 10,
    width: 5,
    height: 34,
    borderRadius: 99,
    background: 'var(--sorin-green-bright)',
  },
  navIcon: { width: 20, fontSize: 22, color: '#7A7B87' },
  navIconActive: { color: 'var(--sorin-green-bright)' },
  navChevron: { marginLeft: 'auto', fontSize: 19, color: '#747580' },
  childStack: {
    margin: '8px 16px 9px 35px',
    paddingLeft: 16,
    borderLeft: '1px solid rgba(40,252,174,0.20)',
    display: 'flex',
    flexDirection: 'column',
    gap: 4,
  },
  childNav: {
    height: 42,
    width: '100%',
    padding: '0 12px',
    display: 'flex',
    alignItems: 'center',
    gap: 10,
    border: 0,
    borderRadius: 10,
    background: 'transparent',
    color: '#6A6B74',
    fontFamily: 'var(--font-sans)',
    fontSize: 22,
    lineHeight: '26px',
    fontWeight: 500,
    textAlign: 'left',
    cursor: 'pointer',
  },
  childNavActive: { background: 'rgba(32,202,139,0.08)' },
  recentsPanel: {
    boxSizing: 'border-box',
    height: 568,
    marginTop: 25,
    padding: '19px 20px',
    border: '1px solid var(--c-line)',
    borderRadius: 20,
    background: 'linear-gradient(180deg, rgba(17,17,18,0.98), rgba(17,17,18,0.78))',
  },
  recentsTitle: { margin: 0, color: 'var(--c-fg)', fontSize: 20, lineHeight: '24px', fontWeight: 700 },
  recentsSub: { margin: '4px 0 0', color: '#747580', fontSize: 18, lineHeight: '24px' },
  recentList: { display: 'flex', flexDirection: 'column', gap: 8, marginTop: 19 },
  recentItem: {
    height: 47,
    display: 'flex',
    alignItems: 'center',
    gap: 12,
    padding: '0 15px',
    border: '1px solid rgba(30,30,31,0.85)',
    borderRadius: 14,
    background: '#121212',
    color: 'var(--c-fg)',
    fontFamily: 'var(--font-sans)',
    fontSize: 17,
    lineHeight: '22px',
    fontWeight: 700,
    textAlign: 'left',
    cursor: 'default',
  },
  recentDot: { width: 8, height: 8, borderRadius: '50%', background: '#3C3C40', flex: '0 0 auto' },
  walletBox: {
    height: 60,
    display: 'flex',
    alignItems: 'center',
    gap: 13,
    marginTop: 'auto',
    padding: '0 14px',
    border: '1px solid var(--c-line)',
    borderRadius: 16,
    background: '#111112',
  },
  walletAvatar: {
    width: 40,
    height: 40,
    borderRadius: '50%',
    background: 'var(--sorin-green-bright)',
  },
  walletText: { color: '#9899A6', fontSize: 17, fontWeight: 700 },
  walletChevron: { marginLeft: 'auto', color: '#747580' },
  main: {
    minWidth: 0,
    boxSizing: 'border-box',
    flex: 1,
    width: '100%',
    maxWidth: 1584,
    marginRight: 'auto',
    display: 'flex',
    flexDirection: 'column',
    gap: 16,
    padding: '29px 18px 26px 24px',
    overflowY: 'auto',
    overflowX: 'hidden',
  },
  mainDense: { padding: '24px 22px 26px' },
  mainCompact: { padding: '20px 18px 28px' },
  mainPhone: { padding: '16px 12px 24px', gap: 12 },
  headerPanel: {
    boxSizing: 'border-box',
    flex: '0 0 auto',
    height: 132,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '23px 30px',
    border: '1px solid rgba(45,45,47,0.8)',
    borderRadius: 24,
    background: 'rgba(17,17,18,0.78)',
  },
  headerPanelDense: { height: 'auto', minHeight: 112, padding: '19px 22px' },
  headerPanelCompact: { alignItems: 'stretch', flexDirection: 'column', gap: 16, borderRadius: 18 },
  headerTitleRow: { display: 'flex', alignItems: 'center', gap: 12 },
  headerTitleRowCompact: { flexWrap: 'wrap' },
  backButton: {
    height: 38,
    display: 'inline-flex',
    alignItems: 'center',
    gap: 8,
    padding: '0 14px',
    border: '1px solid rgba(45,45,47,0.9)',
    borderRadius: 999,
    background: '#070707',
    color: '#B9BAC6',
    fontFamily: 'var(--font-sans)',
    fontSize: 14,
    lineHeight: '18px',
    fontWeight: 700,
    cursor: 'pointer',
  },
  headerPill: {
    display: 'inline-flex',
    alignItems: 'center',
    height: 38,
    padding: '0 19px',
    borderRadius: 99,
    background: 'linear-gradient(180deg, #2D2D2F, #1E1E1F)',
    color: '#B9BAC6',
    fontFamily: 'var(--font-meta)',
    fontSize: 14,
    letterSpacing: '0.35em',
    fontWeight: 700,
  },
  headerCopy: {
    margin: '17px 0 0',
    color: '#B9BAC6',
    fontSize: 20,
    lineHeight: '26px',
    fontWeight: 500,
  },
  headerCopyDense: { marginTop: 13, fontSize: 17, lineHeight: '23px' },
  headerActions: { alignSelf: 'stretch', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 14 },
  headerActionsCompact: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  botCount: { margin: 0, color: '#B9C4E5', fontSize: 21, lineHeight: '25px', fontWeight: 700 },
  botCountSpan: { color: '#747580' },
  botCountLabel: { color: '#747580', fontWeight: 400 },
  headerIconRow: { display: 'flex', gap: 8 },
  iconButton: {
    width: 38,
    height: 38,
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    border: '1px solid rgba(45,45,47,0.92)',
    borderRadius: 10,
    background: '#070707',
    color: '#9899A6',
    fontSize: 20,
    cursor: 'default',
  },
  mainGrid: { display: 'grid', gridTemplateColumns: 'minmax(430px, 496px) minmax(0, 1fr)', gap: 16, minHeight: 'min(804px, calc(100vh - 232px))' },
  mainGridDense: { gridTemplateColumns: 'minmax(330px, 404px) minmax(0, 1fr)', minHeight: 'min(748px, calc(100vh - 214px))' },
  mainGridCompact: { gridTemplateColumns: 'minmax(0, 1fr)', minHeight: 0 },
  botListPanel: {
    boxSizing: 'border-box',
    minHeight: 'min(804px, calc(100vh - 232px))',
    padding: 18,
    border: '1px solid rgba(45,45,47,0.85)',
    borderRadius: 20,
    background: 'rgba(17,17,18,0.72)',
  },
  botListPanelCompact: { minHeight: 0, padding: 14 },
  botCard: {
    width: '100%',
    minHeight: 154,
    padding: '22px 17px 16px',
    border: '1px solid rgba(32,202,139,0.62)',
    borderRadius: 16,
    background: 'rgba(32,202,139,0.05)',
    color: 'var(--c-fg)',
    fontFamily: 'var(--font-sans)',
    textAlign: 'left',
    cursor: 'pointer',
  },
  botCardCompact: { minHeight: 128, padding: '18px 16px 16px' },
  botCardActive: { boxShadow: '0 0 0 1px rgba(40,252,174,0.16) inset', background: 'rgba(32,202,139,0.08)' },
  botCardHeader: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 14 },
  botCardTitle: { margin: 0, color: 'var(--c-fg-strong)', fontSize: 20, lineHeight: '25px', fontWeight: 700 },
  badgeRow: { display: 'flex', gap: 9 },
  badgeBase: {
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    height: 30,
    padding: '0 11px',
    borderRadius: 999,
    fontSize: 14,
    lineHeight: '18px',
    fontWeight: 700,
  },
  paperBadge: {
    border: '1px solid rgba(255,189,76,0.48)',
    background: 'rgba(255,189,76,0.14)',
    color: 'var(--sorin-yellow)',
  },
  armedBadge: {
    border: '1px solid rgba(32,202,139,0.6)',
    background: 'rgba(32,202,139,0.06)',
    color: '#AABDE4',
  },
  pausedBadge: {
    border: '1px solid rgba(255,189,76,0.52)',
    background: 'rgba(255,189,76,0.10)',
    color: '#FFBD4C',
  },
  disarmedBadge: {
    border: '1px solid rgba(116,117,128,0.55)',
    background: 'rgba(116,117,128,0.10)',
    color: '#B9BAC6',
  },
  botListStack: { display: 'flex', flexDirection: 'column', gap: 12 },
  botCardCopy: { margin: '12px 0 0', maxWidth: 390, color: '#B9C4E5', fontSize: 16, lineHeight: '23px', fontWeight: 500 },
  botCardMeta: { margin: '15px 0 0', color: '#747B99', fontSize: 15, lineHeight: '21px' },
  detailPanel: {
    boxSizing: 'border-box',
    minHeight: 'min(804px, calc(100vh - 232px))',
    padding: '22px 17px 17px',
    border: '1px solid rgba(45,45,47,0.85)',
    borderRadius: 20,
    background: 'rgba(17,17,18,0.72)',
    overflow: 'hidden',
  },
  detailPanelDense: { minHeight: 'min(748px, calc(100vh - 214px))' },
  detailPanelCompact: { minHeight: 0, padding: '18px 14px 16px', borderRadius: 18 },
  detailTop: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 18 },
  detailTopCompact: { flexDirection: 'column' },
  detailTitleRow: { display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' },
  detailTitle: { margin: 0, color: 'var(--c-fg-strong)', fontSize: 22, lineHeight: '28px', fontWeight: 700 },
  detailSubtitle: { margin: '4px 0 0', color: '#747B99', fontSize: 15, lineHeight: '20px' },
  detailActions: { display: 'flex', alignItems: 'center', gap: 9 },
  detailActionsCompact: { flexWrap: 'wrap' },
  pauseButton: {
    height: 42,
    padding: '0 14px',
    border: '1px solid rgba(45,45,47,0.92)',
    borderRadius: 10,
    background: '#050505',
    color: '#C3C8E6',
    fontFamily: 'var(--font-sans)',
    fontSize: 19,
    lineHeight: '23px',
    cursor: 'default',
  },
  tabs: { display: 'flex', alignItems: 'center', gap: 7, marginTop: 16, flexWrap: 'wrap' },
  tab: {
    height: 42,
    display: 'inline-flex',
    alignItems: 'center',
    gap: 9,
    padding: '0 12px',
    border: '1px solid rgba(45,45,47,0.92)',
    borderRadius: 9,
    background: '#050505',
    color: '#C3C8E6',
    fontFamily: 'var(--font-sans)',
    fontSize: 19,
    lineHeight: '23px',
    cursor: 'default',
  },
  tabActive: {
    border: '1px solid rgba(32,202,139,0.72)',
    background: 'rgba(32,202,139,0.16)',
    color: 'var(--sorin-green-bright)',
  },
  infoGrid: { display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1fr)', gap: 16, marginTop: 16 },
  infoGridCompact: { gridTemplateColumns: 'minmax(0, 1fr)' },
  infoCard: {
    boxSizing: 'border-box',
    minHeight: 172,
    padding: '17px 18px',
    border: '1px solid rgba(45,45,47,0.85)',
    borderRadius: 16,
    background: 'rgba(3,3,3,0.38)',
  },
  infoCardCompact: { minHeight: 0, padding: '16px 15px' },
  infoCardTall: { height: 426 },
  infoTitle: {
    margin: 0,
    display: 'flex',
    alignItems: 'center',
    gap: 12,
    color: 'var(--c-fg-strong)',
    fontSize: 17,
    lineHeight: '23px',
    fontWeight: 700,
  },
  mandateText: { margin: '18px 0 0', maxWidth: 520, color: '#C5CBE9', fontSize: 16, lineHeight: '25px' },
  divider: { height: 1, margin: '17px 0 20px', background: 'rgba(45,45,47,0.88)' },
  rowStack: { display: 'flex', flexDirection: 'column', gap: 16 },
  detailRow: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 18, fontSize: 16, lineHeight: '22px' },
  detailLabel: { color: '#747B99' },
  detailValue: { color: '#C5CBE9', fontWeight: 500, textAlign: 'right' },
  executionNotice: {
    marginTop: 25,
    padding: '14px 17px',
    minHeight: 107,
    border: '1px solid rgba(32,202,139,0.48)',
    borderRadius: 13,
    background: 'rgba(32,202,139,0.12)',
  },
  executionNoticeTitle: { margin: 0, color: 'var(--sorin-green-bright)', fontSize: 15, lineHeight: '19px', fontWeight: 700 },
  executionNoticeCopy: { display: 'block', marginTop: 8, color: '#C5CBE9', fontSize: 15, lineHeight: '21px' },
  routeStack: { display: 'flex', flexDirection: 'column', gap: 9, marginTop: 13 },
  routeRow: {
    height: 46,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '0 15px',
    borderRadius: 10,
    background: 'rgba(17,17,18,0.82)',
    color: '#C5CBE9',
    fontSize: 16,
  },
  routeStatus: {
    minWidth: 82,
    height: 32,
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    border: '1px solid rgba(32,202,139,0.62)',
    borderRadius: 999,
    color: '#AEEACB',
    fontSize: 15,
    fontWeight: 500,
  },
  tabContentGrid: { display: 'grid', gridTemplateColumns: 'minmax(0, 1.1fr) minmax(0, 0.9fr)', gap: 16, marginTop: 16 },
  tabContentGridCompact: { gridTemplateColumns: 'minmax(0, 1fr)' },
  panelCopy: { margin: '14px 0 0', color: '#9899A6', fontSize: 15, lineHeight: '22px' },
  assetStack: { display: 'flex', flexDirection: 'column', gap: 10, marginTop: 16 },
  assetRow: {
    display: 'grid',
    gridTemplateColumns: 'minmax(120px, 1fr) 150px 145px 110px',
    gap: 14,
    alignItems: 'center',
    padding: '13px 14px',
    borderRadius: 12,
    background: 'rgba(17,17,18,0.82)',
  },
  assetRowCompact: { gridTemplateColumns: 'minmax(0, 1fr) minmax(110px, 0.5fr)', gap: 10 },
  assetSymbol: { display: 'block', color: '#FFFFFF', fontSize: 16, lineHeight: '21px' },
  assetRoute: { display: 'block', color: '#747B99', fontSize: 14, lineHeight: '20px', marginTop: 2 },
  actionRow: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginTop: 20 },
  actionButton: {
    height: 40,
    padding: '0 14px',
    border: '1px solid rgba(40,252,174,0.36)',
    borderRadius: 10,
    background: 'rgba(32,202,139,0.12)',
    color: 'var(--sorin-green-bright)',
    fontFamily: 'var(--font-sans)',
    fontSize: 15,
    lineHeight: '19px',
    fontWeight: 700,
    cursor: 'pointer',
  },
  smallButton: {
    height: 38,
    padding: '0 12px',
    border: '1px solid rgba(45,45,47,0.95)',
    borderRadius: 10,
    background: '#070707',
    color: '#C3C8E6',
    fontFamily: 'var(--font-sans)',
    fontSize: 14,
    lineHeight: '18px',
    fontWeight: 700,
    cursor: 'pointer',
  },
  scheduleRow: {
    minHeight: 68,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: 14,
    padding: '12px 14px',
    borderRadius: 12,
    background: 'rgba(17,17,18,0.82)',
  },
  scheduleTitle: { display: 'block', color: '#FFFFFF', fontSize: 16, lineHeight: '21px' },
  scheduleMeta: { display: 'block', color: '#747B99', fontSize: 14, lineHeight: '20px', marginTop: 3 },
  auditLayout: { marginTop: 18 },
  auditToolbar: { display: 'flex', alignItems: 'center', gap: 9, flexWrap: 'wrap' },
  filterButton: {
    height: 38,
    padding: '0 13px',
    border: '1px solid rgba(45,45,47,0.9)',
    borderRadius: 999,
    background: '#070707',
    color: '#9899A6',
    fontFamily: 'var(--font-sans)',
    fontSize: 14,
    fontWeight: 700,
    cursor: 'pointer',
  },
  filterButtonActive: {
    border: '1px solid rgba(32,202,139,0.56)',
    background: 'rgba(32,202,139,0.12)',
    color: 'var(--sorin-green-bright)',
  },
  auditList: { display: 'flex', flexDirection: 'column', gap: 9, marginTop: 15 },
  auditRow: {
    minHeight: 54,
    display: 'grid',
    gridTemplateColumns: '88px minmax(0, 1fr) 64px',
    alignItems: 'center',
    gap: 16,
    padding: '0 14px',
    borderRadius: 12,
    background: 'rgba(17,17,18,0.82)',
    color: '#C5CBE9',
  },
  auditRowCompact: { gridTemplateColumns: '68px minmax(0, 1fr) 52px', gap: 10 },
  auditKind: { color: '#28FCAE', fontSize: 13, lineHeight: '17px', fontWeight: 700 },
  auditMessage: { color: '#C5CBE9', fontSize: 15, lineHeight: '20px', fontWeight: 500 },
  auditTime: { color: '#747B99', fontSize: 14, textAlign: 'right' },
  toast: {
    position: 'fixed',
    left: '50%',
    bottom: 30,
    zIndex: 120,
    pointerEvents: 'none',
    transform: 'translateX(-50%)',
    minHeight: 44,
    display: 'inline-flex',
    alignItems: 'center',
    gap: 9,
    padding: '0 15px',
    border: '1px solid rgba(32,202,139,0.48)',
    borderRadius: 12,
    background: 'rgba(8,24,18,0.96)',
    color: '#C5CBE9',
    fontFamily: 'var(--font-sans)',
    fontSize: 15,
    boxShadow: '0 18px 70px rgba(0,0,0,0.55)',
  },
  modalBackdrop: {
    position: 'fixed',
    inset: 0,
    zIndex: 110,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    background: 'rgba(0,0,0,0.58)',
  },
  modal: {
    width: 480,
    maxWidth: 'calc(100vw - 48px)',
    padding: 20,
    border: '1px solid rgba(45,45,47,0.95)',
    borderRadius: 18,
    background: '#0A0A0B',
    boxShadow: '0 28px 110px rgba(0,0,0,0.72)',
  },
  modalHeader: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 },
  modalTitle: { margin: 0, color: '#FFFFFF', fontSize: 22, lineHeight: '28px', fontWeight: 700 },
  fieldLabel: {
    display: 'flex',
    flexDirection: 'column',
    gap: 8,
    marginTop: 16,
    color: '#9899A6',
    fontSize: 14,
    lineHeight: '18px',
    fontWeight: 700,
  },
  fieldInput: {
    boxSizing: 'border-box',
    width: '100%',
    minHeight: 44,
    padding: '0 12px',
    border: '1px solid rgba(45,45,47,0.95)',
    borderRadius: 10,
    background: '#050505',
    color: '#FFFFFF',
    fontFamily: 'var(--font-sans)',
    fontSize: 16,
    outline: 'none',
  },
  fieldTextArea: { minHeight: 104, padding: 12, resize: 'vertical', lineHeight: '22px' },
  modalActions: { display: 'flex', justifyContent: 'flex-end', gap: 10, marginTop: 20 },
  secondaryButton: {
    height: 42,
    padding: '0 14px',
    border: '1px solid rgba(45,45,47,0.95)',
    borderRadius: 10,
    background: '#111112',
    color: '#C3C8E6',
    fontFamily: 'var(--font-sans)',
    fontSize: 15,
    fontWeight: 700,
    cursor: 'pointer',
  },
  primaryButton: {
    height: 42,
    padding: '0 16px',
    border: 0,
    borderRadius: 10,
    background: 'linear-gradient(180deg, #28FCAE, #20CA8B)',
    color: '#00140E',
    fontFamily: 'var(--font-sans)',
    fontSize: 15,
    fontWeight: 800,
    cursor: 'pointer',
  },
  dangerButton: {
    height: 42,
    padding: '0 16px',
    border: 0,
    borderRadius: 10,
    background: '#DF1C41',
    color: '#FFFFFF',
    fontFamily: 'var(--font-sans)',
    fontSize: 15,
    fontWeight: 800,
    cursor: 'pointer',
  },
  templateGrid: { display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginTop: 20 },
  templateButton: {
    height: 56,
    border: '1px solid rgba(40,252,174,0.32)',
    borderRadius: 12,
    background: 'rgba(32,202,139,0.10)',
    color: '#C5CBE9',
    fontFamily: 'var(--font-sans)',
    fontSize: 16,
    fontWeight: 800,
    cursor: 'pointer',
  },
  chatDrawer: {
    position: 'fixed',
    top: 70,
    right: 22,
    bottom: 22,
    zIndex: 105,
    width: 420,
    display: 'flex',
    flexDirection: 'column',
    padding: 18,
    border: '1px solid rgba(45,45,47,0.95)',
    borderRadius: 18,
    background: '#0A0A0B',
    boxShadow: '0 24px 120px rgba(0,0,0,0.72)',
  },
  chatDrawerCompact: { top: 62, right: 10, bottom: 10, left: 10, width: 'auto', padding: 14 },
  chatLog: { flex: 1, display: 'flex', flexDirection: 'column', gap: 10, marginTop: 18, overflow: 'auto' },
  chatBubble: {
    maxWidth: '86%',
    margin: 0,
    padding: '10px 12px',
    borderRadius: 12,
    background: '#111112',
    color: '#C5CBE9',
    fontSize: 15,
    lineHeight: '21px',
  },
  chatBubbleUser: { alignSelf: 'flex-end', background: 'rgba(32,202,139,0.14)', color: '#FFFFFF' },
  chatComposer: { display: 'grid', gridTemplateColumns: '1fr 44px', gap: 10, marginTop: 16 },
  chatInput: {
    height: 44,
    padding: '0 12px',
    border: '1px solid rgba(45,45,47,0.95)',
    borderRadius: 10,
    background: '#050505',
    color: '#FFFFFF',
    fontFamily: 'var(--font-sans)',
    fontSize: 15,
    outline: 'none',
  },
  primaryIconButton: {
    width: 44,
    height: 44,
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    border: 0,
    borderRadius: 10,
    background: 'linear-gradient(180deg, #28FCAE, #20CA8B)',
    color: '#00140E',
    fontSize: 20,
    cursor: 'pointer',
  },
  quickMenu: {
    position: 'absolute',
    top: 126,
    right: 78,
    zIndex: 40,
    width: 190,
    padding: 8,
    border: '1px solid rgba(45,45,47,0.95)',
    borderRadius: 12,
    background: '#0A0A0B',
    boxShadow: '0 20px 80px rgba(0,0,0,0.55)',
  },
  quickMenuItem: {
    width: '100%',
    height: 38,
    padding: '0 10px',
    border: 0,
    borderRadius: 9,
    background: 'transparent',
    color: '#C3C8E6',
    fontFamily: 'var(--font-sans)',
    fontSize: 14,
    fontWeight: 700,
    textAlign: 'left',
    cursor: 'pointer',
  },
};

Object.assign(window, { TradingBotsDesktop });
