// ByDuty Guard — App Host
// Renders the phone frame, navigation stack with iOS push transition,
// sheet stack (slide-up), toast, and global modals.

const Host_T = () => window.__BD_THEME__ || window.BD_TOKENS.dark;

// ────────────────────────────────────────────────────────────
// Stack renderer — animates the top two cards with translateX
// ────────────────────────────────────────────────────────────
function NavStack({ stack, transition }) {
  const t = Host_T();
  // We render the last 2 stack entries to support animation.
  const visible = stack.slice(-2);

  return (
    <div style={{ position:'absolute', inset:0, overflow:'hidden' }}>
      {visible.map((entry, i) => {
        const isTop = i === visible.length - 1;
        const Comp = window.Screens[entry.name];
        if (!Comp) return (
          <div key={entry.key} style={{ position:'absolute', inset:0, padding:50, color:t.danger, fontSize:14 }}>
            Missing screen: <b>{entry.name}</b>
          </div>
        );

        // Animation rules:
        // push: incoming top slides from right (100% → 0); previous slides L slightly (-30%)
        // pop : top (departing) slides to right (0 → 100%); below slides back (−30% → 0)
        let style = { position:'absolute', inset:0, transition:'transform 0.32s cubic-bezier(0.32, 0.72, 0, 1), opacity 0.32s', willChange:'transform' };

        if (transition.dir === 'push') {
          if (isTop && transition.to && entry.key === transition.to.key) {
            // incoming
            style.animation = 'bdSlideInR 0.32s cubic-bezier(0.32, 0.72, 0, 1)';
          } else {
            style.animation = 'bdSlideOutL 0.32s cubic-bezier(0.32, 0.72, 0, 1)';
          }
        } else if (transition.dir === 'pop') {
          if (isTop) {
            style.animation = 'bdSlideInL 0.32s cubic-bezier(0.32, 0.72, 0, 1)';
          } else {
            // outgoing departed
          }
        } else if (transition.dir === 'fade') {
          style.animation = 'bdFade 0.2s ease-out';
        }

        return (
          <div key={entry.key} style={style}>
            <div style={{ position:'absolute', inset:0, display:'flex', flexDirection:'column', background: t.bg }}>
              <Comp {...entry.params}/>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Sheet host — slide-up stacked sheets
// ────────────────────────────────────────────────────────────
function SheetHost() {
  const t = Host_T();
  const nav = window.Nav.useNav();
  const sheets = nav.sheets;
  if (sheets.length === 0) return null;

  return (
    <div style={{ position:'absolute', inset:0, zIndex:200 }}>
      {/* backdrop */}
      <div onClick={() => nav.closeSheet()} style={{
        position:'absolute', inset:0, background:'rgba(0,0,0,0.55)',
        animation: 'bdFade 0.2s ease-out', backdropFilter: 'blur(2px)',
      }}/>
      {sheets.map((entry, i) => {
        const Comp = window.Sheets[entry.name];
        const isTop = i === sheets.length - 1;
        return (
          <div key={entry.key} style={{
            position:'absolute', left:0, right:0, bottom:0,
            transform: isTop ? 'translateY(0)' : 'translateY(-12px) scale(0.97)',
            opacity: isTop ? 1 : 0.6,
            transition:'transform 0.28s cubic-bezier(0.32,0.72,0,1), opacity 0.28s',
            animation: 'bdSlideUp 0.32s cubic-bezier(0.32, 0.72, 0, 1)',
          }}>
            {Comp ? <Comp {...entry.params} close={() => nav.closeSheet()}/> :
              <DefaultSheet name={entry.name} close={() => nav.closeSheet()}/>}
          </div>
        );
      })}
    </div>
  );
}

function DefaultSheet({ name, close }) {
  const t = Host_T();
  return (
    <div style={{ background:t.bg2, borderTopLeftRadius:24, borderTopRightRadius:24,
      padding:'12px 18px 32px', borderTop:`1px solid ${t.line}` }}>
      <div style={{ width:36, height:4, borderRadius:999, background:t.line, margin:'4px auto 16px' }}/>
      <div style={{ fontSize:16, fontWeight:700, color:t.text, marginBottom:8 }}>Sheet "{name}" not found</div>
      <window.Button t={t} tone="ghost" full onClick={close}>Close</window.Button>
    </div>
  );
}

// Reusable sheet shell screens use
function Sheet({ title, subtitle, children, close, footer, padded=true }) {
  const t = Host_T();
  return (
    <div style={{
      background:t.bg2, borderTopLeftRadius:24, borderTopRightRadius:24,
      borderTop:`1px solid ${t.line}`, maxHeight:'78%', display:'flex', flexDirection:'column',
      boxShadow: '0 -10px 40px rgba(0,0,0,0.3)',
    }}>
      <div style={{ display:'flex', justifyContent:'center', padding:'8px 0 4px', flexShrink:0 }}>
        <div style={{ width:36, height:4, borderRadius:999, background:t.line }}/>
      </div>
      {(title || subtitle) && (
        <div style={{ padding:'8px 18px 8px', display:'flex', alignItems:'center', justifyContent:'space-between', gap:10, flexShrink:0 }}>
          <div style={{ minWidth:0 }}>
            {subtitle && <div style={{ fontSize:11, color:t.text3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase' }}>{subtitle}</div>}
            {title && <div style={{ fontSize:18, fontWeight:800, color:t.text, letterSpacing:-0.3 }}>{title}</div>}
          </div>
          <button onClick={close} style={{ appearance:'none', cursor:'pointer',
            width:32, height:32, borderRadius:999, border:`1px solid ${t.line}`, background:t.surface,
            color:t.text2, display:'flex', alignItems:'center', justifyContent:'center' }}>
            <window.Icon.X size={16} sw={2.2}/>
          </button>
        </div>
      )}
      <div style={{ flex:1, overflow:'auto', padding: padded ? '6px 18px 14px' : 0 }}>
        {children}
      </div>
      {footer && <div style={{ padding:'10px 16px 30px', borderTop:`1px solid ${t.line}`, flexShrink:0 }}>{footer}</div>}
    </div>
  );
}

// Confirmation dialog (centered modal)
function ConfirmDialog({ title, body, confirmLabel='Confirm', cancelLabel='Cancel', tone='primary', onConfirm, close }) {
  const t = Host_T();
  return (
    <div style={{
      position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center',
      padding:24, animation: 'bdFade 0.2s ease-out',
    }}>
      <div style={{ background:t.surface, borderRadius:20, border:`1px solid ${t.line}`, width:'100%', maxWidth:320,
        boxShadow:'0 30px 80px rgba(0,0,0,0.4)', animation: 'bdScaleIn 0.22s cubic-bezier(0.32,0.72,0,1)' }}>
        <div style={{ padding:'20px 18px 14px', textAlign:'center' }}>
          <div style={{ fontSize:17, fontWeight:800, color:t.text, letterSpacing:-0.2 }}>{title}</div>
          {body && <div style={{ fontSize:13, color:t.text3, marginTop:8, lineHeight:1.5 }}>{body}</div>}
        </div>
        <div style={{ display:'flex', borderTop:`1px solid ${t.line}` }}>
          <button onClick={close} style={{ flex:1, padding:'14px', appearance:'none', cursor:'pointer',
            background:'transparent', border:'none', borderRight:`1px solid ${t.line}`,
            color:t.text2, fontSize:15, fontWeight:600, fontFamily:window.BD_FONT }}>{cancelLabel}</button>
          <button onClick={() => { onConfirm?.(); close?.(); }} style={{ flex:1, padding:'14px', appearance:'none', cursor:'pointer',
            background:'transparent', border:'none',
            color: t[tone] || t.primary, fontSize:15, fontWeight:800, fontFamily:window.BD_FONT }}>{confirmLabel}</button>
        </div>
      </div>
    </div>
  );
}

// Toast
function Toast() {
  const t = Host_T();
  const nav = window.Nav.useNav();
  if (!nav.toast) return null;
  const map = { primary:t.primary, success:t.success, warn:t.warn, danger:t.danger };
  const c = map[nav.toast.tone] || t.primary;
  return (
    <div key={nav.toast.key} style={{
      position:'absolute', left:16, right:16, top:90, zIndex:300,
      background: t.surface, borderRadius:14, border:`1px solid ${t.line}`,
      boxShadow:'0 12px 32px rgba(0,0,0,0.3)',
      padding:'12px 14px', display:'flex', alignItems:'center', gap:10,
      animation:'bdToastIn 0.3s cubic-bezier(0.32,0.72,0,1)',
    }}>
      <div style={{ width:30, height:30, borderRadius:9, background:c+'22', color:c,
        display:'flex', alignItems:'center', justifyContent:'center' }}>
        {nav.toast.tone==='success' ? <window.Icon.Check size={16} sw={2.4}/>
         : nav.toast.tone==='danger' ? <window.Icon.X size={16} sw={2.4}/>
         : nav.toast.tone==='warn'   ? <window.Icon.AlertTri size={16}/>
         : <window.Icon.Info size={16}/>}
      </div>
      <div style={{ flex:1, fontSize:13, fontWeight:600, color:t.text }}>{nav.toast.msg}</div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// AppHost — composes all of the above into the phone frame
// ────────────────────────────────────────────────────────────
function AppHost() {
  const nav = window.Nav.useNav();
  const t = Host_T();

  return (
    <>
      <NavStack stack={nav.stack} transition={nav.transition}/>
      <Toast/>
      <SheetHost/>
    </>
  );
}

window.AppHost = AppHost;
window.Sheet = Sheet;
window.ConfirmDialog = ConfirmDialog;

// Global keyframes injection
if (!document.getElementById('bd-anim-css')) {
  const s = document.createElement('style');
  s.id = 'bd-anim-css';
  s.textContent = `
    @keyframes bdSlideInR { from { transform: translateX(100%); } to { transform: translateX(0); } }
    @keyframes bdSlideInL { from { transform: translateX(-30%); opacity: 0.7; } to { transform: translateX(0); opacity: 1; } }
    @keyframes bdSlideOutL { from { transform: translateX(0); opacity: 1; } to { transform: translateX(-30%); opacity: 0.7; } }
    @keyframes bdSlideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
    @keyframes bdFade { from { opacity: 0; } to { opacity: 1; } }
    @keyframes bdScaleIn { from { opacity: 0; transform: scale(0.92); } to { opacity: 1; transform: scale(1); } }
    @keyframes bdToastIn { from { opacity: 0; transform: translateY(-8px) scale(0.97); } to { opacity:1; transform: translateY(0) scale(1); } }
    @keyframes bdPulse { 0% { transform: scale(1); opacity: 1; } 100% { transform: scale(1.6); opacity: 0; } }
    @keyframes bdSpin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
  `;
  document.head.appendChild(s);
}
