import { useEffect, useState } from 'preact/hooks';

export function Header() {
  const [version, setVersion] = useState('2.0.0');
  const [hasUpdate, setHasUpdate] = useState(false);

  useEffect(() => {
    const checkVersion = async () => {
      try {
        const req = await fetch(
          'https://raw.githubusercontent.com/yoannchb-pro/MoodleGPT/main/package.json'
        );
        const rep = await req.json();
        const lastVersion = rep.version;

        const lastVertionSplitted = lastVersion.split('.');
        const currentVersionSplitted = version.split('.');
        const minVersionLength = Math.min(
          lastVertionSplitted.length,
          currentVersionSplitted.length
        );

        for (let i = 0; i < minVersionLength; ++i) {
          if (parseInt(lastVertionSplitted[i]) > parseInt(currentVersionSplitted[i])) {
            setVersion(lastVersion);
            setHasUpdate(true);
            return;
          } else if (parseInt(currentVersionSplitted[i]) > parseInt(lastVertionSplitted[i])) {
            return;
          }
        }
      } catch (err) {
        console.error(err);
      }
    };
    checkVersion();
  }, []);

  return (
    <div class="flex items-center gap-4 mb-2">
      <img
        src="../icon.png"
        alt="SparkAssist Logo"
        class="w-12 h-12 drop-shadow-md animate-float"
      />
      <div>
        <h1 class="m-0 text-2xl font-bold bg-gradient-to-r from-indigo-300 to-indigo-400 bg-clip-text text-transparent">
          SparkAssist
        </h1>
        <p class="m-0 mt-1 text-xs text-text-secondary">
          {hasUpdate ? (
            <>
              <a
                href="https://github.com/yoannchb-pro/MoodleGPT"
                target="_blank"
                rel="noopener noreferrer"
                class="text-sky-400 no-underline font-medium hover:text-sky-300 transition-colors"
              >
                v{version}
              </a>{' '}
              is now available !
            </>
          ) : (
            `v${version}`
          )}
        </p>
      </div>
    </div>
  );
}
