// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com)
/**
 * GeneratedSnippetCard — live HTML <script> preview the merchant pastes
 * into their site's </body>. Reads from the SAME live form state as
 * SnippetSection, so changing dock/theme/cache-ttl/scenario/deploymentTarget
 * in the editor above updates the snippet immediately.
 *
 * The IntegrationKey is selected (production / testing) and injected as
 * data-integration-key. All other data-* attributes come from the live
 * snippet form — values matching their default are omitted to keep the
 * snippet minimal.
 *
 * Replaces the SnippetConstructor that previously lived inside
 * TenantDetail.tsx — config and snippet now share one source of truth.
 *
 * @layer Presentation
 */

import { useMemo, useState } from 'react';
import { CheckCircle, Copy } from 'lucide-react';
import { useIntegrationKeys } from '@/features/integration-keys/hooks';
import { KeyEnvironment } from '@/domain/entities/IntegrationKey';
import { DEFAULT_FORM, type FormState, type TFunction } from '../lib/constants';

const PLUGIN_CDN_URL = 'https://cdn.twwim.ai/archer.js';

interface GeneratedSnippetCardProps {
  tenantId: string;
  form: FormState;
  t: TFunction;
}

type Env = 'production' | 'testing';

export function GeneratedSnippetCard({ tenantId, form, t }: GeneratedSnippetCardProps) {
  const [selectedEnv, setSelectedEnv] = useState<Env>('production');
  const [copied, setCopied] = useState(false);

  const { keys } = useIntegrationKeys({ tenantId });

  const productionKey = useMemo(
    () => keys.find((k) => k.environment === KeyEnvironment.PRODUCTION) ?? null,
    [keys],
  );
  const testingKey = useMemo(
    () => keys.find((k) => k.environment === KeyEnvironment.TESTING) ?? null,
    [keys],
  );

  const activeKey = useMemo(() => {
    if (selectedEnv === 'production') {
      return productionKey?.key ?? 'YOUR_PRODUCTION_KEY';
    }
    return testingKey?.key ?? 'YOUR_TESTING_KEY';
  }, [selectedEnv, productionKey, testingKey]);

  const snippet = useMemo(() => {
    const snip = form.snippet;
    const def = DEFAULT_FORM.snippet;
    const attrs: string[] = [`data-integration-key="${activeKey}"`];
    if (snip.dock !== def.dock) attrs.push(`data-dock="${snip.dock}"`);
    if (snip.theme !== def.theme) attrs.push(`data-theme="${snip.theme}"`);
    if (snip.uiCacheTTL !== def.uiCacheTTL)
      attrs.push(`data-ui-cache="${snip.uiCacheTTL}"`);
    if (snip.scenario) attrs.push(`data-scenario="${snip.scenario}"`);
    if (snip.domIndexer !== def.domIndexer)
      attrs.push(`data-dom-indexer="${snip.domIndexer ? 'true' : 'false'}"`);
    if (snip.deploymentTarget)
      attrs.push(`data-deployment-target="${snip.deploymentTarget}"`);
    const attrLines = attrs.map((a) => `        ${a}`).join('\n');
    return `<!-- twwim.ai Voice Plugin -->\n<script id="twwim-config"\n${attrLines}>\n</script>\n<script src="${PLUGIN_CDN_URL}" async></script>`;
  }, [form.snippet, activeKey]);

  const handleCopy = async () => {
    await navigator.clipboard.writeText(snippet);
    setCopied(true);
    window.setTimeout(() => setCopied(false), 2000);
  };

  return (
    <section className="bg-white border border-gray-200 rounded-lg shadow-sm p-6 space-y-4">
      <div className="border-b border-gray-100 pb-3">
        <h2 className="text-base font-semibold text-gray-900">
          {t('tenants.pluginSettings.snippetCard.title')}
        </h2>
        <p className="text-xs text-gray-500 mt-0.5">
          {t('tenants.pluginSettings.snippetCard.subtitle')}
        </p>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <div>
          <label className="block text-xs font-medium text-gray-700 mb-1">
            {t('tenants.pluginSettings.snippetCard.keyLabel')}
          </label>
          <select
            value={selectedEnv}
            onChange={(event) => setSelectedEnv(event.target.value as Env)}
            className="w-full px-3 py-2 text-sm border border-gray-300 bg-white rounded-lg focus:ring-2 focus:ring-cyan-500 focus:outline-none"
          >
            <option value="production">
              {t('tenants.pluginSettings.snippetCard.keyProduction')}
            </option>
            <option value="testing">
              {t('tenants.pluginSettings.snippetCard.keyTesting')}
            </option>
          </select>
        </div>
      </div>

      <div className="relative">
        <pre className="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-x-auto text-xs">
          <code>{snippet}</code>
        </pre>
        <button
          type="button"
          onClick={handleCopy}
          className="absolute top-2 right-2 flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-gray-300 bg-gray-800 hover:bg-gray-700 rounded transition-colors"
          aria-label="Copy snippet"
        >
          {copied ? (
            <>
              <CheckCircle size={12} className="text-green-400" />
              {t('common.copied')}
            </>
          ) : (
            <>
              <Copy size={12} />
              {t('common.copy')}
            </>
          )}
        </button>
      </div>
    </section>
  );
}
