/* YeYe Expat Portal — reusable required profile fields card grid */

function requiredFieldLabel(entry, t) {
  const key = 'wizard.field.' + String(entry && entry.key || '');
  return t(key);
}

function requiredFieldValue(value) {
  if (Array.isArray(value)) return value.join(', ');
  if (value && typeof value === 'object') return Object.values(value).filter(Boolean).join(', ');
  return String(value == null ? '' : value).trim();
}

function ProfileMissingFieldsBanner({ contact, edits }) {
  const { t } = useT();
  const missing = window.YEYE_PROFILE && window.YEYE_PROFILE.missing
    ? window.YEYE_PROFILE.missing(contact || {}, edits || {})
    : [];
  if (!missing.length) return null;
  const labels = missing.map((entry) => requiredFieldLabel(entry, t));
  return (
    <Alert
      tone="warn"
      icon="triangle-alert"
      title={t('profileFields.missingBanner').replace('{count}', missing.length)}
    >
      {t('profileFields.missingList')} {labels.join(', ')}
    </Alert>
  );
}

function RequiredFieldsGrid({ contact, onEdit, title }) {
  const { t, lang } = useT();
  const entries = window.YEYE_REQUIRED_FIELDS || [];
  const isFilled = (value) => window.YEYE_PROFILE && window.YEYE_PROFILE.isFilled
    ? window.YEYE_PROFILE.isFilled(value)
    : requiredFieldValue(value).length > 0;
  const fields = entries.map((entry) => {
    const value = window.YEYE_PROFILE && window.YEYE_PROFILE.getValue
      ? window.YEYE_PROFILE.getValue(contact || {}, entry)
      : (contact && contact[entry.key]);
    return { entry, value, filled: isFilled(value) };
  });
  const sectionOrder = fields.reduce((keys, field) => (
    keys.includes(field.entry.section) ? keys : keys.concat(field.entry.section)
  ), []);
  const totalFilled = fields.filter((field) => field.filled).length;

  return (
    <div className="required-fields">
      <ProfileMissingFieldsBanner contact={contact} />
      {title && (
        <div className="required-fields-title">
          <div>
            <div className="eyebrow">{t('profileFields.sectionEyebrow')}</div>
            <h2>{title}</h2>
          </div>
          <span className="required-fields-count">
            {t('profileFields.filledCount').replace('{filled}', totalFilled).replace('{total}', fields.length)}
          </span>
        </div>
      )}
      <div className="required-fields-sections">
        {sectionOrder.map((sectionKey) => {
          const sectionFields = fields.filter((field) => field.entry.section === sectionKey);
          const sectionFilled = sectionFields.filter((field) => field.filled).length;
          const captions = (window.YEYE_REQUIRED_SECTIONS && window.YEYE_REQUIRED_SECTIONS[sectionKey]) || {};
          const sectionLabel = captions[lang] || captions.en || sectionKey;
          return (
            <section className="required-fields-section" key={sectionKey}>
              <header className="required-fields-section-head">
                <h3>{sectionLabel}</h3>
                <span>
                  {t('profileFields.filledCount').replace('{filled}', sectionFilled).replace('{total}', sectionFields.length)}
                </span>
              </header>
              <div className="required-fields-grid">
                {sectionFields.map(({ entry, value, filled }) => {
                  const label = requiredFieldLabel(entry, t);
                  return (
                    <button
                      type="button"
                      className={'required-field-card ' + (filled ? 'is-filled' : 'is-empty')}
                      key={entry.key}
                      onClick={() => onEdit && onEdit(entry)}
                      aria-label={t('profileFields.editField').replace('{field}', label)}
                    >
                      <span className="required-field-label">{label}</span>
                      <span className={'required-field-value ' + (filled ? '' : 'is-empty')}>
                        {filled ? requiredFieldValue(value) : t('profileFields.notFilled')}
                      </span>
                      <span className="required-field-edit" aria-hidden="true"><Icon name="pencil" size={14} /></span>
                    </button>
                  );
                })}
              </div>
            </section>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { ProfileMissingFieldsBanner, RequiredFieldsGrid });
