const BACKEND_BASE_URL = window.BACKEND_BASE_URL || 'https://api.example.com';

let PreferencesImpl = null;

async function getPreferences() {
  if (PreferencesImpl) return PreferencesImpl;
  
  try {
    const module = await import('@capacitor/preferences');
    PreferencesImpl = module.Preferences;
    return PreferencesImpl;
  } catch {
    // Fallback to localStorage
    PreferencesImpl = {
      async get({ key }) {
        return { value: localStorage.getItem(key) };
      },
      async set({ key, value }) {
        localStorage.setItem(key, value);
        return;
      },
      async remove({ key }) {
        localStorage.removeItem(key);
        return;
      },
      async keys() {
        return { keys: Object.keys(localStorage) };
      },
      async clear() {
        localStorage.clear();
        return;
      }
    };
    return PreferencesImpl;
  }
}

export const Preferences = {
  async get(options) {
    const pref = await getPreferences();
    return pref.get(options);
  },
  async set(options) {
    const pref = await getPreferences();
    return pref.set(options);
  },
  async remove(options) {
    const pref = await getPreferences();
    return pref.remove(options);
  },
  async keys() {
    const pref = await getPreferences();
    return pref.keys();
  },
  async clear() {
    const pref = await getPreferences();
    return pref.clear();
  }
};

export async function syncApp(appId) {
  if (!appId || appId.trim() === '') {
    throw new Error('appId is required');
  }
  
  const { value } = await Preferences.get({ key: `app_${appId}` });
  if (!value) {
    throw new Error(`App not found: ${appId}`);
  }
  
  const appData = JSON.parse(value);
  
  const response = await fetch(`${BACKEND_BASE_URL}/desktop/apps/sync`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(appData),
  });
  
  if (!response.ok) {
    throw new Error(`Sync failed: ${response.status}`);
  }
  
  return response.json();
}

export async function runOpencodeTask(appId, taskName, args = []) {
  if (!appId || appId.trim() === '') {
    throw new Error('appId is required');
  }
  if (!taskName || taskName.trim() === '') {
    throw new Error('taskName is required');
  }
  
  throw new Error('OpenCode execution is not supported on mobile devices. Please use the desktop app for this feature.');
}

window.nativeBridge = {
  Preferences,
  syncApp,
  runOpencodeTask
};
