// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com)
/**
 * SnippetSection — server-controlled snippet runtime configuration.
 *
 * Operates on `form.snippet`. Renders:
 *   - theme: 1..50 chars / /^[a-z0-9-]+$/i, text input
 *   - dock: select with the 10 dock positions
 *   - uiCacheTTL: bounded NumberInput (0..86400)
 *   - scenario: optional text input (empty → null)
 *   - domIndexer: sr-only peer-style switch
 *   - deploymentTarget: select with (none) + Shopify
 *
 * @layer Presentation
 */

import type { Dispatch, SetStateAction } from 'react';
import {
  DOCK_OPTIONS,
  type FormState,
  type TFunction,
} from '../lib/constants';
import { NumberInput } from './NumberInput';

interface SnippetSectionProps {
  form: FormState;
  setForm: Dispatch<SetStateAction<FormState>>;
  t: TFunction;
}

const THEME_REGEX = /^[a-z0-9-]+$/i;

export function SnippetSection({ form, setForm, t }: SnippetSectionProps) {
  const snippet = form.snippet;

  const updateSnippet = (changes: Partial<typeof snippet>): void => {
    setForm({
      ...form,
      snippet: { ...snippet, ...changes },
    });
  };

  const themeInvalid =
    snippet.theme.length < 1 ||
    snippet.theme.length > 50 ||
    !THEME_REGEX.test(snippet.theme);
  const scenarioInvalid =
    snippet.scenario !== null &&
    (snippet.scenario.length < 1 || snippet.scenario.length > 50);

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

      {/* theme */}
      <div>
        <label className="block text-xs font-medium text-gray-700 mb-1">
          {t('tenants.pluginSettings.snippet.themeLabel')}
        </label>
        <input
          type="text"
          value={snippet.theme}
          maxLength={50}
          onChange={(e) => updateSnippet({ theme: e.target.value })}
          className={`w-full px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-cyan-500 focus:outline-none ${
            themeInvalid ? 'border-red-400 bg-red-50' : 'border-gray-300 bg-white'
          }`}
        />
        <p className="text-xs text-gray-500 mt-1">
          {t('tenants.pluginSettings.snippet.themeHelp')}
        </p>
      </div>

      {/* dock */}
      <div>
        <label className="block text-xs font-medium text-gray-700 mb-1">
          {t('tenants.pluginSettings.snippet.dockLabel')}
        </label>
        <select
          value={snippet.dock}
          onChange={(e) => {
            const next = e.target.value;
            const dock = DOCK_OPTIONS.find((opt) => opt === next);
            if (dock !== undefined) updateSnippet({ dock });
          }}
          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"
        >
          {DOCK_OPTIONS.map((opt) => (
            <option key={opt} value={opt}>
              {t(`tenants.pluginSettings.snippet.dockOption.${opt}`)}
            </option>
          ))}
        </select>
        <p className="text-xs text-gray-500 mt-1">
          {t('tenants.pluginSettings.snippet.dockHelp')}
        </p>
      </div>

      {/* uiCacheTTL */}
      <NumberInput
        label={t('tenants.pluginSettings.snippet.uiCacheTtlLabel')}
        help={t('tenants.pluginSettings.snippet.uiCacheTtlHelp')}
        min={0}
        max={86400}
        value={snippet.uiCacheTTL}
        onChange={(v) => updateSnippet({ uiCacheTTL: v })}
      />

      {/* scenario */}
      <div>
        <label className="block text-xs font-medium text-gray-700 mb-1">
          {t('tenants.pluginSettings.snippet.scenarioLabel')}
        </label>
        <input
          type="text"
          value={snippet.scenario ?? ''}
          maxLength={50}
          onChange={(e) => {
            const next = e.target.value;
            updateSnippet({ scenario: next.length === 0 ? null : next });
          }}
          className={`w-full px-3 py-2 text-sm border rounded-lg focus:ring-2 focus:ring-cyan-500 focus:outline-none ${
            scenarioInvalid ? 'border-red-400 bg-red-50' : 'border-gray-300 bg-white'
          }`}
        />
        <p className="text-xs text-gray-500 mt-1">
          {t('tenants.pluginSettings.snippet.scenarioHelp')}
        </p>
      </div>

      {/* domIndexer */}
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm font-medium text-gray-900">
            {t('tenants.pluginSettings.snippet.domIndexerLabel')}
          </p>
          <p className="text-xs text-gray-500 mt-0.5">
            {t('tenants.pluginSettings.snippet.domIndexerHelp')}
          </p>
        </div>
        <label className="inline-flex items-center cursor-pointer">
          <input
            type="checkbox"
            checked={snippet.domIndexer}
            onChange={(e) => updateSnippet({ domIndexer: e.target.checked })}
            className="sr-only peer"
          />
          <span className="relative w-11 h-6 bg-gray-200 rounded-full peer peer-checked:bg-cyan-600 transition-colors after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-transform peer-checked:after:translate-x-5" />
        </label>
      </div>

      {/* deploymentTarget */}
      <div>
        <label className="block text-xs font-medium text-gray-700 mb-1">
          {t('tenants.pluginSettings.snippet.deploymentTargetLabel')}
        </label>
        <select
          value={snippet.deploymentTarget ?? ''}
          onChange={(e) => {
            const next = e.target.value;
            if (next === '') {
              updateSnippet({ deploymentTarget: null });
            } else if (next === 'shopify') {
              updateSnippet({ deploymentTarget: 'shopify' });
            }
          }}
          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="">
            {t('tenants.pluginSettings.snippet.deploymentTargetNone')}
          </option>
          <option value="shopify">
            {t('tenants.pluginSettings.snippet.deploymentTargetShopify')}
          </option>
        </select>
        <p className="text-xs text-gray-500 mt-1">
          {t('tenants.pluginSettings.snippet.deploymentTargetHelp')}
        </p>
      </div>
    </section>
  );
}
