import styled from "@emotion/styled"
import { useTranslation } from "react-i18next"
import { memo } from "react"
import { Entry } from "./Entry"
import { Section } from "./style"
import type { Data } from "../App"
import { usePopupContext } from "../index"

const isApplicableURL = (url: string) => !!url && /^(file|https?|ftps?):/.test(url)

export const Sections = memo<{ files: [string, Data[]][] }>(({ files }) => {
  const { t } = useTranslation()
  const { url } = usePopupContext()

  if (!isApplicableURL(url)) {
    return (
      <Section>
        <NotApplicable>{t("popup.unavailableForURL")}</NotApplicable>
      </Section>
    )
  }

  if (!files.length) {
    return (
      <Section>
        <Installed>{t("popup.noStylesForSite")}</Installed>
      </Section>
    )
  }

  return (
    <Section>
      <Installed>
        {files
          .slice()
          .sort(([tagA], [tagB]) => tagA.localeCompare(tagB))
          .map(([tag, sections]) => (
            <Entry key={tag} tag={tag} files={sections} />
          ))}
      </Installed>
    </Section>
  )
})

const NotApplicable = styled.div`
  color: #777;
  font-style: italic;
  margin: 2px 0 0;
`

const Installed = styled.div`
  margin-top: 0.2em;
`
