/* YeYe Expat Portal — shared profile field widgets */

function normalizeProfileDate(value) {
  const raw = String(value || '').trim();
  if (/^\d{4}-\d{2}-\d{2}/.test(raw)) return raw.slice(0, 10);
  if (/^\d+$/.test(raw) && raw.length >= 10) {
    try { return new Date(Number(raw)).toISOString().slice(0, 10); } catch (_) {}
  }
  return '';
}

function profileCountryOptions(lang) {
  const source = (window.YEYE_PHONE && (window.YEYE_PHONE.COUNTRIES || window.YEYE_PHONE.countries))
    || window.YEYE_COUNTRIES
    || [];
  const fallback = [
    { code: 'CZ', name: 'Czech Republic' },
    { code: 'TR', name: 'Türkiye' },
    { code: 'DE', name: 'Germany' },
    { code: 'AT', name: 'Austria' },
    { code: 'SK', name: 'Slovakia' },
    { code: 'PL', name: 'Poland' },
    { code: 'GB', name: 'United Kingdom' },
    { code: 'US', name: 'United States' },
  ];
  const countries = Array.isArray(source) && source.length ? source : fallback;
  const countryLabel = (country) => {
    const name = country && (country.name || country.names || country.label);
    if (name && typeof name === 'object') return name[lang] || name.en || name.tr || name.cs || country.code || '';
    return String(name || country.en || country.code || '');
  };
  return { countries, countryLabel };
}

function renderProfileFieldWidget({
  kind,
  value,
  onChange,
  options,
  label,
  lang = 'en',
  placeholder = '',
  style,
  className = '',
}) {
  const currentValue = value == null ? '' : String(value);
  const inputClass = ('input ' + className).trim();

  if (kind === 'date') {
    return (
      <input
        type="date"
        className={inputClass}
        style={style}
        value={normalizeProfileDate(currentValue)}
        aria-label={label}
        onChange={(event) => onChange && onChange(event.target.value)}
      />
    );
  }

  if (kind === 'select' && options && options.length) {
    return (
      <select
        className={inputClass}
        style={style}
        value={currentValue}
        aria-label={label}
        onChange={(event) => onChange && onChange(event.target.value)}
      >
        <option value="">{placeholder}</option>
        {options.map((option) => {
          const optionValue = typeof option === 'object' ? option.value : option;
          const optionLabel = typeof option === 'object' ? option.label : option;
          return <option key={optionValue} value={optionValue}>{optionLabel}</option>;
        })}
      </select>
    );
  }

  if (kind === 'country') {
    const { countries, countryLabel } = profileCountryOptions(lang);
    const normalize = (candidate) => String(candidate || '').trim().toLowerCase();
    const rawCountry = currentValue.trim();
    const rawUpper = rawCountry.toUpperCase();
    const byCode = countries.find((country) => String(country.code || '').toUpperCase() === rawUpper);
    const byName = countries.find((country) => normalize(countryLabel(country)) === normalize(rawCountry) || normalize(country.name) === normalize(rawCountry));
    const selectedCountry = byCode || byName;
    const selectedValue = selectedCountry ? String(selectedCountry.code || '').toUpperCase() : rawCountry;
    const showRawFallback = rawCountry && !selectedCountry;
    return (
      <select
        className={inputClass}
        style={style}
        value={selectedValue}
        aria-label={label}
        onChange={(event) => {
          const code = String(event.target.value || '').toUpperCase();
          const picked = countries.find((country) => String(country.code || '').toUpperCase() === code);
          const output = picked ? String(picked.name || countryLabel(picked) || code) : (event.target.value || '');
          onChange && onChange(output);
        }}
      >
        <option value="">{placeholder}</option>
        {showRawFallback && <option value={rawCountry}>{rawCountry}</option>}
        {countries.map((country) => {
          const code = String(country.code || '').toUpperCase();
          if (!code) return null;
          return <option key={code} value={code}>{countryLabel(country)}</option>;
        })}
      </select>
    );
  }

  if (kind === 'phone' && window.YEYE_PhoneInput && window.YEYE_PHONE) {
    const split = window.YEYE_PHONE.splitE164(currentValue);
    return (
      <div className={'profile-phone-widget ' + className} style={style}>
        <window.YEYE_PhoneInput
          countryCode={split.country}
          localNumber={split.local}
          onCountryChange={(code) => onChange && onChange(window.YEYE_PHONE.toE164(code, split.local))}
          onLocalChange={(digits) => onChange && onChange(window.YEYE_PHONE.toE164(split.country, digits))}
        />
      </div>
    );
  }

  return (
    <input
      className={inputClass}
      type={kind === 'email' ? 'email' : (kind === 'number' ? 'number' : 'text')}
      style={style}
      value={currentValue}
      aria-label={label}
      placeholder={placeholder}
      onChange={(event) => onChange && onChange(event.target.value)}
    />
  );
}

Object.assign(window, {
  renderProfileFieldWidget,
  YEYE_NORMALIZE_PROFILE_DATE: normalizeProfileDate,
});
