/* global React */
const { useState } = React;

// ---------- Belgian formatting ----------
function formatBelgianMoney(raw) {
  if (raw === '' || raw == null) return '';
  const cleaned = String(raw).replace(/[^\d,]/g, '');
  const [intPart, decPart] = cleaned.split(',');
  if (!intPart) return decPart != null ? '0,' + decPart : '';
  const grouped = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, '\u202F');
  return decPart != null ? grouped + ',' + decPart : grouped;
}

// ---------- Phone ----------
const PHONE_COUNTRIES = {
  BE: { dial: '32', maxLen: 9, placeholder: '4 __ __ __ __' },
  FR: { dial: '33', maxLen: 9, placeholder: '6 __ __ __ __' },
  LU: { dial: '352', maxLen: 9, placeholder: '6_ __ __ __' },
  NL: { dial: '31', maxLen: 9, placeholder: '6 ____ ____' },
  DE: { dial: '49', maxLen: 11, placeholder: '1__ _______' },
  CH: { dial: '41', maxLen: 9, placeholder: '7_ ___ __ __' },
  GB: { dial: '44', maxLen: 10, placeholder: '7___ ______' },
  XX: { dial: '', maxLen: 15, placeholder: 'international' }
};

function phoneLocalDigits(raw, country) {
  if (!raw) return '';
  let digits = String(raw).replace(/\D/g, '');
  const c = PHONE_COUNTRIES[country] || PHONE_COUNTRIES.BE;
  if (digits.startsWith('00')) digits = digits.slice(2);
  if (c.dial && digits.startsWith(c.dial)) digits = digits.slice(c.dial.length);
  if (digits.startsWith('0')) digits = digits.replace(/^0+/, '');
  return digits.slice(0, c.maxLen);
}

function formatPhoneNumber(raw, country) {
  const c = PHONE_COUNTRIES[country] || PHONE_COUNTRIES.BE;
  const local = phoneLocalDigits(raw, country);
  const prefix = c.dial ? '+' + c.dial : '';
  if (!local) return prefix;
  let parts = [];
  if (country === 'BE') {
    if (local.startsWith('4')) {
      parts = [local.slice(0, 3), local.slice(3, 5), local.slice(5, 7), local.slice(7, 9)];
    } else {
      parts = [local.slice(0, 1), local.slice(1, 3), local.slice(3, 5), local.slice(5, 7), local.slice(7, 9)];
    }
  } else if (country === 'FR') {
    parts = [local.slice(0, 1), local.slice(1, 3), local.slice(3, 5), local.slice(5, 7), local.slice(7, 9)];
  } else if (country === 'LU') {
    parts = [local.slice(0, 3), local.slice(3, 6), local.slice(6, 9)];
  } else if (country === 'NL') {
    parts = local.startsWith('6') ?
    [local.slice(0, 1), local.slice(1, 5), local.slice(5, 9)] :
    [local.slice(0, 2), local.slice(2, 5), local.slice(5, 9)];
  } else {
    parts = [local.slice(0, 3), local.slice(3, 5), local.slice(5, 7), local.slice(7, 9), local.slice(9)];
  }
  parts = parts.filter(Boolean);
  return prefix + (prefix && parts.length ? ' ' : '') + parts.join(' ');
}

// ---------- Field ----------
function Field({ label, hint, required, children, className = '' }) {
  return (
    <label className={'field ' + className}>
      {label ?
      <span className="field__label">
          {label}
          {required ? <span className="field__required" aria-label="champ requis" /> : null}
        </span> :
      null}
      {children}
      {hint ? <span className="field__hint">{hint}</span> : null}
    </label>);

}

// ---------- Inputs ----------
function TextInput({ value, onChange, placeholder, type = 'text', ...rest }) {
  return (
    <input
      className="input"
      type={type}
      value={value || ''}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      {...rest} />);


}

function Textarea({ value, onChange, placeholder, large, rows }) {
  return (
    <textarea
      className={'textarea' + (large ? ' textarea--lg' : '')}
      value={value || ''}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      rows={rows} />);


}

function MoneyInput({ value, onChange, placeholder }) {
  return (
    <div className="input-wrap">
      <input
        className="input"
        type="text"
        inputMode="decimal"
        value={formatBelgianMoney(value || '')}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder} />
      
      <span className="input-wrap__suffix">€</span>
    </div>);

}

function SurfaceInput({ value, onChange, placeholder = '0' }) {
  return (
    <div className="input-wrap">
      <input
        className="input"
        type="text"
        inputMode="decimal"
        value={value || ''}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder} />
      
      <span className="input-wrap__suffix">m²</span>
    </div>);

}

function PhoneInput({ value, onChange, country = 'BE', onCountryChange }) {
  const c = PHONE_COUNTRIES[country] || PHONE_COUNTRIES.BE;
  return (
    <div className="phone-input">
      <select
        className="phone-input__country"
        value={country}
        onChange={(e) => {
          const next = e.target.value;
          const local = phoneLocalDigits(value, country);
          onCountryChange && onCountryChange(next);
          onChange(formatPhoneNumber(local, next));
        }}
        aria-label="Indicatif pays">
        
        {Object.entries(PHONE_COUNTRIES).map(([code, info]) =>
        <option key={code} value={code}>
            {code}{info.dial ? '  +' + info.dial : ''}
          </option>
        )}
      </select>
      <input
        className="phone-input__number"
        type="tel"
        value={value || ''}
        onChange={(e) => onChange(formatPhoneNumber(e.target.value, country))}
        placeholder={c.placeholder} />
      
    </div>);

}

// ---------- Unified pill group (segmented / yes-no / radio with dot) ----------
function PillGroup({ value, onChange, options, fill = false, withDot = false }) {
  return (
    <div className={'pill-group' + (fill ? ' pill-group--fill' : '')} role="radiogroup">
      {options.map((opt) => {
        const v = typeof opt === 'object' ? opt.value : opt;
        const label = typeof opt === 'object' ? opt.label : opt;
        const on = value === v;
        return (
          <button
            key={String(v)}
            type="button"
            role="radio"
            aria-checked={on}
            className={'pill-group__btn' + (on ? ' is-on' : '')}
            onClick={() => onChange(v)}>
            
            {withDot ? <span className="pill-group__dot" aria-hidden="true" /> : null}
            {label}
          </button>);

      })}
    </div>);

}

function YesNo({ value, onChange, fill = false }) {
  return (
    <PillGroup
      value={value}
      onChange={onChange}
      options={[{ value: true, label: 'Oui' }, { value: false, label: 'Non' }]}
      fill={fill} />);


}

function ChipGroup({ values = [], onChange, options, fill = false, variant }) {
  const set = new Set(values);
  const toggle = (v) => {
    const next = new Set(set);
    if (next.has(v)) next.delete(v);else next.add(v);
    onChange(Array.from(next));
  };
  // 'pill' variant renders as a pill-style segmented group (no checkmark) but still multi-select
  if (variant === 'pill') {
    return (
      <div className="pill-group pill-group--fill" role="group">
        {options.map((opt) => {
          const v = typeof opt === 'object' ? opt.value : opt;
          const label = typeof opt === 'object' ? opt.label : opt;
          const on = set.has(v);
          return (
            <button
              key={String(v)}
              type="button"
              aria-pressed={on}
              className={'pill-group__btn' + (on ? ' is-on' : '')}
              onClick={() => toggle(v)}>
              {label}
            </button>);
        })}
      </div>);
  }
  return (
    <div className={'chips' + (fill ? ' chips--fill' : '')} role="group">
      {options.map((opt) => {
        const v = typeof opt === 'object' ? opt.value : opt;
        const label = typeof opt === 'object' ? opt.label : opt;
        const on = set.has(v);
        return (
          <button
            key={String(v)}
            type="button"
            aria-pressed={on}
            className={'chip' + (on ? ' is-on' : '')}
            onClick={() => toggle(v)}>

            <span className="chip__check" />
            {label}
          </button>);

      })}
    </div>);

}

Object.assign(window, {
  formatBelgianMoney, formatPhoneNumber,
  Field, TextInput, Textarea, MoneyInput, SurfaceInput, PhoneInput,
  PillGroup, YesNo, ChipGroup
});