const fs = require('fs');
const path = require('path');

const html = fs.readFileSync(path.join(__dirname, '../public/index.html'), 'utf8');

// Mock HTML elements from index.html
const elements = {};
const matchIds = html.match(/id="([^"]+)"/g) || [];
matchIds.forEach(idAttr => {
  const id = idAttr.split('"')[1];
  elements[id] = {
    id,
    addEventListener: (event, cb) => {},
    style: {},
    classList: {
      add: () => {},
      remove: () => {},
      contains: () => false
    },
    querySelectorAll: () => []
  };
});

global.document = {
  readyState: 'complete',
  documentElement: {
    setAttribute: (name, val) => {},
    getAttribute: (name) => 'dark'
  },
  getElementById: (id) => {
    if (!elements[id]) {
      console.warn(`[Warning] getElementById: ID "${id}" not found in index.html!`);
      return null;
    }
    return elements[id];
  },
  querySelector: (selector) => {
    return {
      addEventListener: () => {},
      style: {},
      classList: { add: () => {}, remove: () => {} }
    };
  },
  querySelectorAll: (selector) => {
    return [];
  },
  createElement: (tag) => {
    return { style: {}, classList: { add: () => {} } };
  },
  body: {
    appendChild: () => {}
  },
  addEventListener: (event, cb) => {
    if (event === 'DOMContentLoaded') {
      cb();
    }
  }
};

global.window = {
  location: { href: '' },
  speechSynthesis: {
    getVoices: () => [],
    addEventListener: () => {}
  },
  document: global.document
};

global.localStorage = {
  getItem: () => null,
  setItem: () => {},
  removeItem: () => {}
};

global.marked = {
  Renderer: function() {},
  use: () => {}
};

global.navigator = {
  clipboard: {}
};

// Mock fetch to not crash Node
global.fetch = () => new Promise((resolve) => resolve({
  ok: true,
  json: () => Promise.resolve({ success: true, observations: [] }),
  text: () => Promise.resolve('')
}));

try {
  console.log("Loading public/app.js with proper mock...");
  require('../public/app.js');
  console.log("Successfully ran public/app.js without throwing errors!");
} catch (err) {
  console.error("FATAL ERROR running app.js:", err);
}
