/* Viamar Ops — app shell (sidebar + topbar + routing) */

function OpsSidebar({ tab, onTab }) {
  const nav = [
    { id: 'overview', icon: 'home', label: 'Overview' },
    { id: 'quotes', icon: 'spark', label: 'Quote queue', badge: '3' },
    { id: 'shipments', icon: 'ship', label: 'Shipments' },
    { id: 'inbox', icon: 'phone', label: 'Inbox', badge: '2' },
    { id: 'insights', icon: 'waves', label: 'Insights' },
  ];
  return (
    <div style={{ width: 232, flexShrink: 0, background: T.navy, display: 'flex', flexDirection: 'column', padding: '22px 14px' }}>
      <div style={{ padding: '4px 8px 22px' }}>
        <ViamarLogo width={138} onDark />
        <div style={{ fontFamily: FM, fontSize: 8, letterSpacing: 2.5, color: 'rgba(255,255,255,0.45)', marginTop: 4 }}>OPERATIONS CONSOLE</div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4, flex: 1 }}>
        {nav.map(it => {
          const active = tab === it.id;
          return (
            <div key={it.id} onClick={() => onTab(it.id)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 13px', borderRadius: 12, cursor: 'pointer', background: active ? 'rgba(255,255,255,0.08)' : 'transparent', transition: 'background .15s' }}
              onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'rgba(255,255,255,0.04)'; }}
              onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
              <Icon name={it.icon} size={20} color={active ? '#fff' : 'rgba(255,255,255,0.55)'} stroke={active ? 2.2 : 1.9} />
              <span style={{ flex: 1, fontFamily: FB, fontWeight: active ? 700 : 600, fontSize: 13.5, color: active ? '#fff' : 'rgba(255,255,255,0.6)' }}>{it.label}</span>
              {it.badge && <span style={{ fontFamily: FM, fontSize: 10, fontWeight: 700, color: '#fff', background: T.red, borderRadius: 999, minWidth: 18, height: 18, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '0 5px' }}>{it.badge}</span>}
            </div>
          );
        })}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: 8, borderTop: '1px solid rgba(255,255,255,0.08)', marginTop: 8, paddingTop: 16 }}>
        <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'linear-gradient(135deg,#2C5172,#112A44)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: FD, fontWeight: 800, fontSize: 14, color: '#fff', flexShrink: 0 }}>M</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: FB, fontWeight: 700, fontSize: 13, color: '#fff' }}>Marco Rossi</div>
          <div style={{ fontFamily: FM, fontSize: 9.5, color: 'rgba(255,255,255,0.5)' }}>Operations agent</div>
        </div>
      </div>
    </div>
  );
}

const OPS_META = {
  overview: { title: 'Operations', sub: 'Today · Courtice warehouse' },
  quotes: { title: 'Quote queue', sub: 'Review, price & confirm' },
  shipments: { title: 'Shipments', sub: 'Live pipeline' },
  inbox: { title: 'Support inbox', sub: 'Customer conversations' },
  insights: { title: 'Insights', sub: 'Funnel & analytics' },
};

function OpsTopBar({ meta, onToast }) {
  const [apiState, setApiState] = React.useState(() => ({
    configured: !!(window.ViamarAPI && ViamarAPI.configured()),
    hasToken: !!(window.ViamarAPI && ViamarAPI.hasToken()),
    base: window.ViamarAPI && ViamarAPI.apiBase ? ViamarAPI.apiBase() : '',
  }));
  const [exporting, setExporting] = React.useState(false);
  const [features, setFeatures] = React.useState(() => (
    window.ViamarAPI && ViamarAPI.features ? ViamarAPI.features() : {
      quotes: true,
      uploads: true,
      payments: true,
      recovery: true,
      events: true,
    }
  ));
  React.useEffect(() => {
    const onApiConfig = (event) => setApiState(event.detail || {
      configured: !!(window.ViamarAPI && ViamarAPI.configured()),
      hasToken: !!(window.ViamarAPI && ViamarAPI.hasToken()),
      base: window.ViamarAPI && ViamarAPI.apiBase ? ViamarAPI.apiBase() : '',
    });
    const onFeatures = (event) => setFeatures(event.detail || (window.ViamarAPI && ViamarAPI.features ? ViamarAPI.features() : features));
    window.addEventListener('viamar:api-config', onApiConfig);
    window.addEventListener('viamar:features', onFeatures);
    if (window.ViamarAPI && ViamarAPI.refreshConfig) {
      ViamarAPI.refreshConfig().then(cfg => {
        if (cfg && cfg.features) setFeatures(cfg.features);
      }).catch(() => {});
    }
    return () => {
      window.removeEventListener('viamar:api-config', onApiConfig);
      window.removeEventListener('viamar:features', onFeatures);
    };
  }, []);
  const setupApi = () => {
    if (!window.ViamarAPI || !ViamarAPI.configure) {
      if (onToast) onToast('API bridge is not loaded');
      return;
    }
    const currentBase = ViamarAPI.apiBase ? ViamarAPI.apiBase() : '';
    const base = window.prompt('Worker API base URL', currentBase || 'https://api.viamar.com');
    if (base === null) return;
    const token = window.prompt('Ops bearer token (ALEX_API_TOKEN or WORKER_AUTH_TOKEN)', '');
    if (token === null) return;
    const next = ViamarAPI.configure({ base, token });
    setApiState(next);
    if (onToast) onToast(next.configured && next.hasToken ? 'Live API token saved for this browser' : 'API settings updated');
  };
  const clearApiToken = () => {
    if (!window.ViamarAPI || !ViamarAPI.configure) {
      if (onToast) onToast('API bridge is not loaded');
      return;
    }
    if (!window.confirm('Clear the saved ops bearer token from this browser?')) return;
    const next = ViamarAPI.configure({ token: '' });
    setApiState(next);
    if (onToast) onToast('Ops token cleared for this browser');
  };
  const statusText = apiState.configured && apiState.hasToken ? 'Live API' : apiState.configured ? 'Token needed' : 'Demo mode';
  const statusColor = apiState.configured && apiState.hasToken ? T.green : apiState.configured ? T.amber : T.muted;
  const disabledFeatures = Object.entries(features || {}).filter(([, enabled]) => enabled === false).map(([name]) => name);
  const featureText = disabledFeatures.length ? 'Disabled: ' + disabledFeatures.join(', ') : 'All app features on';
  const featureColor = disabledFeatures.length ? T.red : T.green;
  const refreshFeatures = () => {
    if (!(window.ViamarAPI && ViamarAPI.refreshConfig)) {
      if (onToast) onToast('Feature config is not available');
      return;
    }
    ViamarAPI.refreshConfig().then(cfg => {
      const nextFeatures = cfg && cfg.features ? cfg.features : features;
      const nextDisabled = Object.entries(nextFeatures || {}).filter(([, enabled]) => enabled === false).map(([name]) => name);
      if (cfg && cfg.features) setFeatures(cfg.features);
      if (onToast) onToast(nextDisabled.length ? 'Disabled features: ' + nextDisabled.join(', ') : 'Feature flags refreshed');
    }).catch(err => {
      if (onToast) onToast('Could not refresh feature flags: ' + err.message);
    });
  };
  const exportCsv = () => {
    if (!(window.ViamarAPI && ViamarAPI.exportRecords)) {
      if (onToast) onToast('Export helper is not loaded');
      return;
    }
    if (!(window.ViamarAPI.configured && ViamarAPI.configured() && ViamarAPI.hasToken && ViamarAPI.hasToken())) {
      if (onToast) onToast('Set Live API and ops token before exporting');
      return;
    }
    setExporting(true);
    ViamarAPI.exportRecords({ days: 30, limit: 500 }).then(result => {
      if (onToast) onToast('CSV export downloaded' + (result && result.bytes ? ' · ' + result.bytes + ' bytes' : ''));
    }).catch(err => {
      if (onToast) onToast('CSV export failed: ' + err.message);
    }).finally(() => setExporting(false));
  };
  return (
    <div style={{ height: 70, flexShrink: 0, borderBottom: '1px solid ' + T.line, background: '#fff', display: 'flex', alignItems: 'center', padding: '0 36px', gap: 18 }}>
      <div style={{ flex: 1 }}>
        <Display size={19} color={T.ink}>{meta.title}</Display>
        <div style={{ fontFamily: FM, fontSize: 10.5, color: T.muted, letterSpacing: 0.3, marginTop: 2 }}>{meta.sub}</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, background: T.paper, borderRadius: 12, padding: '9px 13px', width: 250, border: '1px solid ' + T.line2 }}>
        <Icon name="search" size={16} color={T.faint} stroke={2} />
        <input placeholder="Search ref, customer, vessel" style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontFamily: FB, fontSize: 12.5, color: T.ink }} />
      </div>
      <div onClick={setupApi} title={apiState.base || 'Set Worker API'} style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#fff', border: '1px solid ' + T.line2, borderRadius: 12, padding: '10px 12px', cursor: 'pointer' }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: statusColor }} />
        <span style={{ fontFamily: FM, fontSize: 10.5, fontWeight: 700, color: statusColor, textTransform: 'uppercase', letterSpacing: 0.5 }}>{statusText}</span>
      </div>
      {apiState.hasToken && (
        <div onClick={clearApiToken} title="Clear saved ops bearer token" style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#fff', border: '1px solid ' + T.line2, borderRadius: 12, padding: '10px 12px', cursor: 'pointer' }}>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: T.amber }} />
          <span style={{ fontFamily: FM, fontSize: 10.5, fontWeight: 700, color: T.amber, textTransform: 'uppercase', letterSpacing: 0.5, whiteSpace: 'nowrap' }}>Clear token</span>
        </div>
      )}
      <div onClick={refreshFeatures} title={featureText} style={{ display: 'flex', alignItems: 'center', gap: 8, background: disabledFeatures.length ? 'rgba(221,28,36,0.08)' : '#fff', border: '1px solid ' + (disabledFeatures.length ? 'rgba(221,28,36,0.22)' : T.line2), borderRadius: 12, padding: '10px 12px', cursor: 'pointer', maxWidth: 230 }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: featureColor }} />
        <span style={{ fontFamily: FM, fontSize: 10.5, fontWeight: 700, color: featureColor, textTransform: 'uppercase', letterSpacing: 0.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{disabledFeatures.length ? disabledFeatures.length + ' flag off' : 'Features on'}</span>
      </div>
      <div onClick={exporting ? undefined : exportCsv} title="Export recent app records as CSV" style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#fff', border: '1px solid ' + T.line2, borderRadius: 12, padding: '10px 12px', cursor: exporting ? 'wait' : 'pointer', opacity: exporting ? 0.68 : 1 }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: T.navy3 }} />
        <span style={{ fontFamily: FM, fontSize: 10.5, fontWeight: 700, color: T.navy3, textTransform: 'uppercase', letterSpacing: 0.5, whiteSpace: 'nowrap' }}>{exporting ? 'Exporting' : 'Export CSV'}</span>
      </div>
      <div style={{ position: 'relative', width: 40, height: 40, borderRadius: 11, background: T.paper, border: '1px solid ' + T.line2, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name="bell" size={19} color={T.navy} stroke={1.9} />
        <span style={{ position: 'absolute', top: 9, right: 10, width: 7, height: 7, borderRadius: '50%', background: T.red, border: '1.5px solid #fff' }} />
      </div>
    </div>
  );
}

function OpsApp() {
  const [tab, setTab] = React.useState('overview');
  const [toast, setToast] = React.useState(null);
  const fireToast = (m) => { setToast(m); setTimeout(() => setToast(null), 3200); };

  let screen;
  if (tab === 'overview') screen = <OverviewScreen onNav={setTab} />;
  else if (tab === 'quotes') screen = <QuoteQueueScreen onToast={fireToast} />;
  else if (tab === 'shipments') screen = <ShipmentsBoardScreen onToast={fireToast} />;
  else if (tab === 'inbox') screen = <InboxScreen onToast={fireToast} />;
  else screen = <InsightsScreen />;

  return (
    <div style={{ height: '100%', display: 'flex', background: T.paper, position: 'relative', overflow: 'hidden' }}>
      <OpsSidebar tab={tab} onTab={setTab} />
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        <OpsTopBar meta={OPS_META[tab]} onToast={fireToast} />
        <div key={tab} className="screenfade" style={{ flex: 1, minHeight: 0, position: 'relative' }}>{screen}</div>
      </div>
      {toast && (
        <div style={{ position: 'absolute', left: '50%', transform: 'translateX(-50%)', bottom: 26, zIndex: 95, background: T.navy, color: '#fff', borderRadius: 14, padding: '13px 18px', display: 'flex', alignItems: 'center', gap: 11, boxShadow: '0 16px 40px rgba(0,0,0,0.4)', border: '1px solid rgba(255,255,255,0.1)' }}>
          <div style={{ width: 25, height: 25, borderRadius: '50%', background: T.green, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="check" size={14} color="#fff" stroke={3} /></div>
          <span style={{ fontFamily: FB, fontWeight: 600, fontSize: 13 }}>{toast}</span>
        </div>
      )}
    </div>
  );
}

function Root() {
  return (
    <div id="stage" style={{ height: '100vh', minHeight: 720, background: T.paper, overflow: 'hidden' }}>
      <OpsApp />
    </div>
  );
}

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