function createPraxisBanner(content) {
  const banner = document.createElement('div');
  banner.id = 'praxis-banner';
  banner.innerHTML = content;

  Object.assign(banner.style, {
    position: 'sticky',
    top: '0',
    left: '0',
    width: '100%',
    padding: '12px',
    backgroundColor: '#374151',
    color: '#f3f4f6',
    textAlign: 'center',
    zIndex: '999999',
    fontSize: '16px',
    boxSizing: 'border-box',
    borderBottom: '1px solid #4b5563'
  });

  document.body.prepend(banner);
  return banner;
}

(async () => {
  const headlineElement = document.querySelector("h1");
  const headlineText = headlineElement ? headlineElement.textContent : null;

  if (!headlineText) {
    return;
  }

  const ISSUES = [
    { value: "gun-control", text: "Gun Control" },
    { value: "gun-rights", text: "Gun Rights" },
    { value: "privacy", text: "Electronic Privacy" },
    { value: "immigration", text: "Immigration" },
    { value: "climate-change", text: "Climate Change" },
    { value: "healthcare", text: "Healthcare" },
    { value: "racial-justice", text: "Racial Justice" },
    { value: "lgbtq-rights", text: "LGBTQ+ Rights" },
    { value: "economic-inequality", text: "Economic Inequality" },
    { value: "reproductive-rights", text: "Reproductive Rights" },
    { value: "education-reform", text: "Education Reform" },
    { value: "criminal-justice", text: "Criminal Justice" },
    { value: "voting-rights", text: "Voting Rights" },
    { value: "campaign-finance", text: "Campaign Finance" },
    { value: "foreign-policy", text: "Foreign Policy" },
    { value: "national-security", text: "National Security" },
    { value: "free-speech", text: "Free Speech" },
    { value: "net-neutrality", text: "Net Neutrality" },
    { value: "labor-rights", text: "Labor Rights" },
    { value: "affordable-housing", text: "Affordable Housing" },
    { value: "environmental-protection", text: "Environmental Protection" },
    { value: "space-exploration", text: "Space Exploration" },
    { value: "drug-policy-reform", text: "Drug Policy Reform" },
    { value: "veterans-affairs", text: "Veterans' Affairs" },
    { value: "senior-citizen-rights", text: "Senior Citizen Rights" },
  ];

  const issueTitlesMap = new Map(ISSUES.map(issue => [issue.value, issue.text]));

  const donationLinks = {
    "gun-control": [
      { "name": "Brady United", "url": "https://www.bradyunited.org/donate" },
      { "name": "Everytown for Gun Safety", "url": "https://www.everytown.org/donate/" },
      { "name": "Moms Demand Action", "url": "https://momsdemandaction.org/donate/"}
    ],
    "gun-rights": [
      { "name": "Gun Owners of America", "url": "https://www.gunowners.org/donate/" },
      { "name": "National Rifle Association (NRA)", "url": "https://donate.nra.org/donate" },
      { "name": "Second Amendment Foundation (SAF)", "url": "https://www.saf.org/donate/"}
    ],
    "privacy": [
      { "name": "Electronic Frontier Foundation (EFF)", "url": "https://www.eff.org/donate" },
      { "name": "ACLU", "url": "https://www.aclu.org/donate/join-aclu-renew-your-membership" },
      { "name": "Privacy Rights Clearinghouse", "url": "https://privacyrights.org/donate"}
    ],
    "immigration": [
      { "name": "ACLU Immigrants' Rights Project", "url": "https://www.aclu.org/issues/immigrants-rights/donate" },
      { "name": "National Immigration Law Center (NILC)", "url": "https://www.nilc.org/donate/" },
      { "name": "Kids in Need of Defense (KIND)", "url": "https://supportkind.org/donate/"}
    ],
    "climate-change": [
      { "name": "Earthjustice", "url": "https://www.earthjustice.org/donate" },
      { "name": "Natural Resources Defense Council (NRDC)", "url": "https://www.nrdc.org/donate" },
      { "name": "Environmental Defense Fund (EDF)", "url": "https://www.edf.org/donate"}
    ],
    "healthcare": [
      { "name": "Families USA", "url": "https://www.familiesusa.org/donate/" },
      { "name": "Planned Parenthood", "url": "https://www.plannedparenthood.org/donate" },
      { "name": "Doctors Without Borders", "url": "https://give.doctorswithoutborders.org/campaign/675296/donate"}
    ],
    "racial-justice": [
      { "name": "NAACP Legal Defense and Educational Fund (NAACP LDF)", "url": "https://www.naacpldf.org/donate/" },
      { "name": "Southern Poverty Law Center (SPLC)", "url": "https://www.splcenter.org/support-us" },
      { "name": "Black Lives Matter Global Network Foundation", "url": "https://blacklivesmatter.com/donate/"}
    ],
    "lgbtq-rights": [
      { "name": "Lambda Legal", "url": "https://www.lambdalegal.org/donate" },
      { "name": "Human Rights Campaign (HRC)", "url": "https://www.hrc.org/donate" },
      { "name": "The Trevor Project", "url": "https://www.thetrevorproject.org/donate/"}
    ],
    "economic-inequality": [
      { "name": "National Employment Law Project (NELP)", "url": "https://www.nelp.org/donate/" },
      { "name": "Economic Policy Institute (EPI)", "url": "https://www.epi.org/donate/" },
      { "name": "Oxfam America", "url": "https://www.oxfamamerica.org/donate/"}
    ],
    "reproductive-rights": [
      { "name": "Reproductive Freedom for All", "url": "https://act.reprofreedomforall.org/a/donate" },
      { "name": "Planned Parenthood", "url": "https://www.plannedparenthood.org/donate" },
      { "name": "National Abortion Federation (NAF)", "url": "https://prochoice.org/donate/"}
    ],
    "education-reform": [
      { "name": "The Education Trust", "url": "https://edtrust.org/donate/" },
      { "name": "DonorsChoose", "url": "https://www.donorschoose.org/donate" },
      { "name": "Teach for America", "url": "https://www.teachforamerica.org/donate"}
    ],
    "criminal-justice": [
      { "name": "Justice in Aging", "url": "https://www.justiceinaging.org/donate/" },
      { "name": "The Sentencing Project", "url": "https://www.sentencingproject.org/donate/" },
      { "name": "Innocence Project", "url": "https://innocenceproject.org/donate/" },
      { "name": "Drug Policy Alliance", "url": "https://drugpolicy.org/donate" }
    ],
    "voting-rights": [
      { "name": "Brennan Center for Justice", "url": "https://www.brennancenter.org/donate" },
      { "name": "Fair Fight", "url": "https://fairfight.com/invest/" },
      { "name": "League of Women Voters", "url": "https://www.lwv.org/donate"}
    ],
    "campaign-finance": [
      { "name": "Campaign Legal Center", "url": "https://campaignlegal.org/donate" },
      { "name": "OpenSecrets (Center for Responsive Politics)", "url": "https://www.opensecrets.org/donate" },
      { "name": "Common Cause", "url": "https://www.commoncause.org/donate/"}
    ],
    "foreign-policy": [
      { "name": "Council on Foreign Relations (CFR)", "url": "https://www.cfr.org/support-cfr" },
      { "name": "Carnegie Endowment for International Peace", "url": "https://carnegieendowment.org/donate/" },
      { "name": "United Nations Foundation", "url": "https://unfoundation.org/donate/"}
    ],
    "national-security": [
      { "name": "Center for Strategic and International Studies (CSIS)", "url": "https://www.csis.org/donate" },
      { "name": "Atlantic Council", "url": "https://www.atlanticcouncil.org/support/" },
      { "name": "Union of Concerned Scientists (UCS)", "url": "https://www.ucsusa.org/donate"}
    ],
    "free-speech": [
      { "name": "Foundation for Individual Rights and Expression (FIRE)", "url": "https://www.thefire.org/donate" },
      { "name": "ACLU", "url": "https://www.aclu.org/donate/join-aclu-renew-your-membership" },
      { "name": "PEN America", "url": "https://pen.org/donate/"}
    ],
    "net-neutrality": [
      { "name": "Free Press", "url": "https://www.freepress.net/donate/" },
      { "name": "Electronic Frontier Foundation (EFF)", "url": "https://www.eff.org/donate" },
      { "name": "Demand Progress", "url": "https://demandprogress.org/donate/"}
    ],
    "labor-rights": [
      { "name": "AFL-CIO", "url": "https://aflcio.org/about/ways-to-give" },
      { "name": "National Labor Law Project", "url": "https://www.nationallaborlawproject.org/donate/"},
      { "name": "United Farm Workers (UFW)", "url": "https://ufw.org/donate/"}
    ],
    "affordable-housing": [
      { "name": "National Low Income Housing Coalition (NLIHC)", "url": "https://nlihc.org/donate" },
      { "name": "Habitat for Humanity", "url": "https://www.habitat.org/donate" },
      { "name": "Enterprise Community Partners", "url": "https://www.enterprisecommunity.org/donate"}
    ],
    "environmental-protection": [
      { "name": "Natural Resources Defense Council (NRDC)", "url": "https://www.nrdc.org/donate" },
      { "name": "Sierra Club", "url": "https://www.sierraclub.org/donate" },
      { "name": "World Wildlife Fund (WWF)", "url": "https://www.worldwildlife.org/donate"}
    ],
    "space-exploration": [
      { "name": "The Planetary Society", "url": "https://www.planetary.org/donate" },
      { "name": "National Space Society", "url": "https://space.nss.org/donate/" },
      { "name": "Space Foundation", "url": "https://www.spacefoundation.org/support-us/"}
    ],
    "drug-policy-reform": [
      { "name": "Drug Policy Alliance", "url": "https://drugpolicy.org/donate" },
      { "name": "NORML", "url": "https://norml.org/donate/" },
      { "name": "Marijuana Policy Project (MPP)", "url": "https://www.mpp.org/donate/"}
    ],
    "veterans-affairs": [
      { "name": "Iraq and Afghanistan Veterans of America (IAVA)", "url": "https://www.iava.org/donate/" },
      { "name": "Wounded Warrior Project", "url": "https://www.woundedwarrior.org/donate" },
      { "name": "Gary Sinise Foundation", "url": "https://www.garysinisefoundation.org/donate"}
    ],
    "senior-citizen-rights": [
      { "name": "Justice in Aging", "url": "https://www.justiceinaging.org/donate/" },
      { "name": "AARP Foundation", "url": "https://www.aarp.org/giving/" },
      { "name": "National Council on Aging (NCOA)", "url": "https://www.ncoa.org/donate"}
    ],
    "disability-rights": [
      { "name": "Disability Rights Education and Defense Fund (DREDF)", "url": "https://dredf.org/donate/" },
      { "name": "American Association of People with Disabilities (AAPD)", "url": "https://www.aapd.com/donate/" }
    ],
    "animal-welfare": [
      { "name": "ASPCA (American Society for the Prevention of Cruelty to Animals)", "url": "https://www.aspca.org/donate" },
      { "name": "Humane Society of the United States (HSUS)", "url": "https://www.humanesociety.org/donate" }
    ],
    "arts-culture": [
      { "name": "National Endowment for the Arts (NEA)", "url": "https://www.arts.gov/support-nea" },
      { "name": "Americans for the Arts", "url": "https://www.americansforthearts.org/donate" }
    ],
    "child-welfare": [
      { "name": "Childhelp", "url": "https://www.childhelp.org/donate/" },
      { "name": " Prevent Child Abuse America", "url": "https://preventchildabuse.org/donate/" }
    ]
  };

  let praxisBanner = null;

  const sendSentimentAnalysisRequest = async () => {
    const response = await chrome.runtime.sendMessage({
      type: "ANALYZE_SENTIMENT",
      payload: { headline: headlineText }
    });

    if (response.type === "ANALYSIS_RESULT" && response.result && response.result.sentiment) {
      const sentiment = response.result.sentiment;
      if (sentiment === 'negative' || sentiment === 'depressing' || sentiment === 'worrying') {
        sendCategoryAnalysisRequest();
      } else {
        return;
      }
    } else if (response.type === "LLM_ERROR") {
      return;
    } else {
      return;
    }
  };

  const sendCategoryAnalysisRequest = async () => {
    const storageApi = typeof browser !== 'undefined' && browser.storage ? browser.storage.local : (typeof chrome !== 'undefined' && chrome.storage ? chrome.storage.sync : null);
    let selectedIssues = [];
    if (storageApi) {
      try {
        const data = await storageApi.get('selected_issues');
        if (data && data.selected_issues) {
          selectedIssues = data.selected_issues;
        }
      } catch (error) {
      }
    }

    const response = await chrome.runtime.sendMessage({
      type: "ANALYZE_HEADLINE_CATEGORY",
      payload: { 
        headline: headlineText,
        selectedIssues: selectedIssues
      }
    });

    if (response.type === "ANALYSIS_RESULT" && response.result && response.result.categories && response.result.categories.length > 0) {
      let donateLinksHtml = '';
      response.result.categories.forEach(category => {
        const organizations = donationLinks[category];
        if (organizations && organizations.length > 0) {
          const niceCategoryTitle = issueTitlesMap.get(category) || category.replace(/-/g, ' ');
          donateLinksHtml += `<strong>${niceCategoryTitle}:</strong> `;
          const categoryOrgLinks = organizations.map(org =>
            `<a href="${org.url}" target="_blank" style="color: #60a5fa; text-decoration: underline;">${org.name}</a>`
          ).join(', ');
          donateLinksHtml += `${categoryOrgLinks}<br>`;
        } else {
        }
      });

      if (donateLinksHtml) {
        praxisBanner = createPraxisBanner(`Based on this news article, you can donate to the following impact organizations:<br>${donateLinksHtml}`);
      } else {
      }
    } else if (response.type === "LLM_ERROR") {
      return;
    } else {
      return;
    }
  };

  sendSentimentAnalysisRequest();
})();