'use client';

import { useEffect, useMemo, useState } from 'react';
import { fetchPublicSettingsClient } from '@/lib/api';
import { buildOneTapExamples, buildOneTapUrls } from '@/lib/one-tap-examples';
import { resolveFrontendBase, resolveOAuthApiBase } from '@/lib/oauth-url';
import { CodeExampleTabs } from '@/components/code-example-tabs';

export function OneTapCodeTabs() {
  const [apiBase, setApiBase] = useState('http://localhost:3000');
  const [frontendBase, setFrontendBase] = useState('http://localhost:3002');
  const [projectName, setProjectName] = useState('MVK ID');

  useEffect(() => {
    void fetchPublicSettingsClient()
      .then((settings) => {
        setApiBase(resolveOAuthApiBase(settings));
        setFrontendBase(resolveFrontendBase(settings));
        if (settings.PROJECT_NAME?.trim()) {
          setProjectName(settings.PROJECT_NAME.trim());
        }
      })
      .catch(() => undefined);
  }, []);

  const urls = useMemo(() => buildOneTapUrls(apiBase, frontendBase, projectName), [apiBase, frontendBase, projectName]);
  const examples = useMemo(() => buildOneTapExamples(urls), [urls]);

  return (
    <div className="space-y-3">
      <p className="text-sm text-zinc-500 dark:text-zinc-400">
        API (issuer): <code className="rounded bg-zinc-100 px-1.5 py-0.5 dark:bg-zinc-800">{apiBase}</code>
        {' · '}
        Frontend / виджет: <code className="rounded bg-zinc-100 px-1.5 py-0.5 dark:bg-zinc-800">{frontendBase}</code>
        {' — '}
        из настроек <strong>PUBLIC_API_URL</strong>, <strong>PUBLIC_FRONTEND_URL</strong> и <strong>PROJECT_NAME</strong>.
      </p>
      <CodeExampleTabs examples={examples} />
    </div>
  );

}
