'use strict';
// This adapter runs inside /nh/. Components, styles and validation come from Home.
window.HubCardPreview = {
  start({root,registerManifestCatalog,widgetData,LauncherTile,WidgetCard,icons,colors}) {
    document.body.className='card-preview min-h-0 bg-canvas';
    const send=message=>parent.postMessage(message,location.origin);
    const path=value=>{
      if(typeof value!=='string'||!/^\/(?!\/)/.test(value)||/[\\\s]/.test(value)||/(^|\/)\.\.?($|\/)/.test(value.split(/[?#]/)[0])||/%2e|%2f|%5c/i.test(value.split(/[?#]/)[0]))throw Error('Page URLs must be provider-relative paths, such as /apps/approvals.');
      return '/px/playground'+value;
    };
    const messageClass='p-5 [font:13px/1.6_system-ui] [overflow-wrap:anywhere]';
    root.render(<p className={messageClass + ' text-muted'}>Waiting for a card…</p>);
    if(parent===window)return;
    window.addEventListener('message',event=>{
      if(event.source!==parent||event.origin!==location.origin||event.data?.type!=='hub-card-preview')return;
      const {requestId,catalog,kind,size,dark}=event.data;
      try {
        if(!catalog||JSON.stringify(catalog).length>100000||!['app','widget'].includes(kind))throw Error('Invalid preview request.');
        if(!Array.isArray(catalog.apps)||catalog.apps.length!==(kind==='app'?1:0)||!Array.isArray(catalog.widgets)||catalog.widgets.length!==(kind==='widget'?1:0))throw Error('Preview one app or widget at a time.');
        const app=catalog.apps[0],definition=catalog.widgets[0];
        const check=entry=>{
          if(typeof entry.id!=='string'||!entry.id||entry.id.length>200||['__proto__','constructor','prototype'].includes(entry.id))throw Error('Enter a unique item ID under 200 characters.');
          if(typeof entry.title!=='string'||!entry.title.trim()||entry.title.length>100)throw Error('Enter a title under 100 characters.');
          if(entry.contextLabel?.length>120)throw Error('Context must be under 120 characters.');
        };
        check(app||definition);
        const dataKey='card-playground-data';
        if(definition)widgetData[dataKey]=definition.data;
        const compiled=registerManifestCatalog({folders:[],apps:app?[{...app,providerName:'Example provider',url:path(app.url)}]:[],widgets:definition?[{...definition,providerName:'Example provider',proxyPrefix:'/px/playground/',...(definition.url===undefined?{}:{url:path(definition.url)}),data:dataKey}]:[]});
        if(compiled.errors.length)throw Error(compiled.errors[0].message);
        const [w,rows]=String(size).split('x').map(Number);
        if(![1,2,3,4,5,6].includes(w)||![1,2,3].includes(rows)||definition&&!definition.sizes.includes(size))throw Error('Choose one of the supported sizes.');
        document.body.classList.toggle('dark',!!dark);
        const onAction=action=>{
          const target=new URL(action.url,location.origin);
          send({type:'hub-card-preview-action',url:target.href.replace(location.origin+'/px/playground','')});
        };
        const node=kind==='app'
          ?(
            <LauncherTile
              entry={{
                id: 'playground-app',
                app: compiled.apps[0]
              }}
              container="home"
              arranging={false}
              showContext={true}
              onLaunch={() => onAction(compiled.apps[0].action)}
            />
          )
          :<WidgetCard key={requestId} widget={compiled.widgets[0]} onAction={onAction} />;
        root.render((
          <div className="preview-stage launcher-grid-shell flex min-h-screen min-w-0 items-start justify-center p-5">
            <div
              className={'grid-cell relative min-w-0 shrink' + (kind === 'widget' ? ' widget-cell' : '')}
              style={{
                width: 'min(100%, ' + (w * 240 + (w - 1) * 16) + 'px)',
                height: rows * 188 + (rows - 1) * 16 + 'px'
              }}
            >
              {node}
            </div>
          </div>
        ));
        send({type:'hub-card-preview-result',requestId,valid:true});
      } catch(error) {
        root.render((
          <p className={messageClass + ' text-danger'} role="alert">
            {error.message}
          </p>
        ));
        send({type:'hub-card-preview-result',requestId,valid:false,error:error.message});
      }
    });
    send({type:'hub-card-preview-ready',icons:[...icons],colors:[...colors]});
  }
};
