/**
 * Org Detector Content Script
 *
 * Detects which Filevine organization the user is currently viewing.
 * This helps when a user has multiple Filevine accounts open in different tabs.
 */

/**
 * Extract current org ID from the page
 * Filevine may store this in various places
 */
export function detectCurrentOrg() {
  // Method 1: Check URL for org ID
  const urlOrgMatch = window.location.pathname.match(/\/org\/(\d+)/);
  if (urlOrgMatch) {
    const orgId = urlOrgMatch[1];
    console.log('[Org Detector] Found org ID in URL:', orgId);
    return { orgId, source: 'url' };
  }

  // Method 2: Check localStorage for current org
  try {
    const possibleKeys = [
      'fv_current_org',
      'current_org',
      'selectedOrg',
      'orgId',
      'currentOrgId'
    ];

    for (const key of possibleKeys) {
      const value = localStorage.getItem(key);
      if (value) {
        try {
          const parsed = JSON.parse(value);
          if (parsed.id || parsed.orgId) {
            const orgId = String(parsed.id || parsed.orgId);
            console.log('[Org Detector] Found org ID in localStorage:', orgId);
            return { orgId, source: 'localStorage', key };
          }
        } catch {
          // Not JSON, might be plain org ID
          if (value.match(/^\d+$/)) {
            console.log('[Org Detector] Found org ID in localStorage:', value);
            return { orgId: value, source: 'localStorage', key };
          }
        }
      }
    }

    // Also check for keys containing "org"
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key && key.toLowerCase().includes('org')) {
        const value = localStorage.getItem(key);
        try {
          const parsed = JSON.parse(value);
          if (parsed.id || parsed.orgId) {
            const orgId = String(parsed.id || parsed.orgId);
            console.log('[Org Detector] Found org ID in localStorage key:', key, orgId);
            return { orgId, source: 'localStorage', key };
          }
        } catch {
          // Ignore
        }
      }
    }
  } catch (error) {
    console.error('[Org Detector] Error checking localStorage:', error);
  }

  // Method 3: Check window object for Filevine state
  try {
    const stateKeys = [
      '__FILEVINE_STATE__',
      '__APP_STATE__',
      '__INITIAL_STATE__',
      'filevineConfig',
      'appConfig'
    ];

    for (const key of stateKeys) {
      if (window[key]) {
        const state = window[key];
        if (state.org?.id) {
          const orgId = String(state.org.id);
          console.log('[Org Detector] Found org ID in window state:', orgId);
          return { orgId, source: 'window', key };
        }
        if (state.currentOrg?.id) {
          const orgId = String(state.currentOrg.id);
          console.log('[Org Detector] Found org ID in window state:', orgId);
          return { orgId, source: 'window', key };
        }
        if (state.user?.orgId) {
          const orgId = String(state.user.orgId);
          console.log('[Org Detector] Found org ID in window state:', orgId);
          return { orgId, source: 'window', key };
        }
      }
    }
  } catch (error) {
    console.error('[Org Detector] Error checking window state:', error);
  }

  // Method 4: Look for org info in DOM (org selector, header, etc.)
  try {
    // Common selectors that might contain org info
    const selectors = [
      '[data-org-id]',
      '[data-orgid]',
      '[data-organization-id]',
      '.org-selector',
      '.organization-selector',
      '#org-selector'
    ];

    for (const selector of selectors) {
      const element = document.querySelector(selector);
      if (element) {
        const orgId = element.dataset.orgId ||
                     element.dataset.orgid ||
                     element.dataset.organizationId ||
                     element.getAttribute('data-org-id') ||
                     element.getAttribute('data-orgid');

        if (orgId) {
          console.log('[Org Detector] Found org ID in DOM:', orgId);
          return { orgId: String(orgId), source: 'dom', selector };
        }
      }
    }
  } catch (error) {
    console.error('[Org Detector] Error checking DOM:', error);
  }

  // Method 5: Extract from subdomain if it's an org-specific subdomain
  try {
    const hostname = window.location.hostname;
    const subdomain = hostname.split('.')[0];

    // If subdomain is not "app" or "www", it might be an org identifier
    if (subdomain !== 'app' && subdomain !== 'www' && subdomain !== 'product') {
      console.log('[Org Detector] Found potential org subdomain:', subdomain);
      return { orgId: subdomain, source: 'subdomain', subdomain };
    }
  } catch (error) {
    console.error('[Org Detector] Error checking subdomain:', error);
  }

  console.log('[Org Detector] Could not detect current org');
  return null;
}

/**
 * Extract org name from the page if possible
 */
export function detectOrgName() {
  try {
    // Look for org name in common places
    const selectors = [
      '.org-name',
      '.organization-name',
      '[data-org-name]',
      '.org-selector .selected',
      '#org-name'
    ];

    for (const selector of selectors) {
      const element = document.querySelector(selector);
      if (element) {
        const name = element.textContent?.trim() || element.dataset.orgName;
        if (name && name.length > 0 && name.length < 100) {
          console.log('[Org Detector] Found org name:', name);
          return name;
        }
      }
    }

    // Check window state
    if (window.__FILEVINE_STATE__?.org?.name) {
      return window.__FILEVINE_STATE__.org.name;
    }
    if (window.__APP_STATE__?.org?.name) {
      return window.__APP_STATE__.org.name;
    }
  } catch (error) {
    console.error('[Org Detector] Error detecting org name:', error);
  }

  return null;
}

/**
 * Watch for org changes (when user switches orgs in the UI)
 */
export function watchForOrgChanges(callback) {
  console.log('[Org Detector] Setting up org change detection...');

  let currentOrg = detectCurrentOrg();

  // Watch for URL changes
  const originalPushState = history.pushState;
  const originalReplaceState = history.replaceState;

  history.pushState = function(...args) {
    originalPushState.apply(history, args);
    checkForOrgChange();
  };

  history.replaceState = function(...args) {
    originalReplaceState.apply(history, args);
    checkForOrgChange();
  };

  window.addEventListener('popstate', checkForOrgChange);

  // Watch for DOM changes (org selector)
  const observer = new MutationObserver(() => {
    checkForOrgChange();
  });

  observer.observe(document.body, {
    childList: true,
    subtree: true,
    attributes: true,
    attributeFilter: ['data-org-id', 'data-orgid']
  });

  function checkForOrgChange() {
    const newOrg = detectCurrentOrg();
    if (newOrg && newOrg.orgId !== currentOrg?.orgId) {
      console.log('[Org Detector] Org changed from', currentOrg?.orgId, 'to', newOrg.orgId);
      currentOrg = newOrg;
      callback(newOrg);
    }
  }

  // Check every few seconds as backup
  setInterval(checkForOrgChange, 3000);

  return () => {
    observer.disconnect();
  };
}
