/* YeYe Expat Portal — v17 persistent onboarding nudges (page-scoped dismiss) */

const NUDGE_PASSPORT_UPLOAD_FIELD_ID = 'afLvwJvs0e3V8CalIC7T';
const NUDGE_PASSPORT_UPLOAD_FIELD_KEY = 'contact.passport_upload';

function OnboardingNudgeCard({ kind, icon, title, sub, cta, onAction, onDismiss }) {
  const { t } = useT();
  const touchStart = React.useRef(null);
  const finishSwipe = (event) => {
    if (!touchStart.current || !event.changedTouches || !event.changedTouches[0]) return;
    const end = event.changedTouches[0];
    const dx = end.clientX - touchStart.current.x;
    const dy = end.clientY - touchStart.current.y;
    touchStart.current = null;
    if (Math.abs(dx) > 55 || dy > 55) onDismiss();
  };

  return (
    <section
      className={'onboarding-nudge onboarding-nudge-' + kind}
      onTouchStart={(event) => {
        const touch = event.touches && event.touches[0];
        touchStart.current = touch ? { x: touch.clientX, y: touch.clientY } : null;
      }}
      onTouchEnd={finishSwipe}
    >
      <button type="button" className="onboarding-nudge-close" onClick={onDismiss} aria-label={t('c.close')}>
        <Icon name="x" size={15} />
      </button>
      <div className="onboarding-nudge-icon"><Icon name={icon} size={19} /></div>
      <div className="onboarding-nudge-copy">
        <h2>{title}</h2>
        <p>{sub}</p>
        <button type="button" className="onboarding-nudge-cta" onClick={onAction}>{cta}</button>
      </div>
    </section>
  );
}

function hasPassportUploaded(contact) {
  const fields = (contact && contact.customFields) || (contact && contact.raw && contact.raw.customFields) || [];
  for (const f of fields) {
    const id = String(f.id || '');
    const key = String(f.key || f.name || '').toLowerCase();
    if (id === NUDGE_PASSPORT_UPLOAD_FIELD_ID || key === NUDGE_PASSPORT_UPLOAD_FIELD_KEY || key.includes('passport_upload') || key.includes('contact__passport_upload')) {
      const value = f.value || f.fileValues || f.fileUrl || '';
      if (Array.isArray(value)) return value.length > 0;
      if (typeof value === 'object' && value) return !!(value.url || value.webViewLink || Object.keys(value).length);
      return !!String(value || '').trim();
    }
  }
  return false;
}

function OnboardingNudges({ blankProfile, contact, page }) {
  return null;
  const { t } = useT();
  const [profileDismissed, setProfileDismissed] = React.useState(false);
  const [servicesDismissed, setServicesDismissed] = React.useState(false);
  const [passportDismissed, setPassportDismissed] = React.useState(false);
  const [servicesReady, setServicesReady] = React.useState(false);
  const [wizardOpen, setWizardOpen] = React.useState(false);

  React.useEffect(() => {
    setProfileDismissed(false);
    setServicesDismissed(false);
    setPassportDismissed(false);
    setServicesReady(false);
    const t = window.setTimeout(() => setServicesReady(true), 1400);
    return () => window.clearTimeout(t);
  }, [page]);

  const profile = window.YEYE_PROFILE && window.YEYE_PROFILE.completeness
    ? window.YEYE_PROFILE.completeness(contact || {})
    : { missing: 0, ratio: 1 };
  const showProfile = !profileDismissed && profile.ratio < 0.6;
  const passportMissing = !!contact && !hasPassportUploaded(contact);
  const excludedPage = page === 'services' || page === 'formSubmission' || page === 'documents';

  const openPassportUpload = () => {
    if (!window.YEYE_GO || !contact) return;
    const contactId = contact.contactId || contact.id || '';
    if (window.YEYE_OPEN_MODAL) {
      window.YEYE_OPEN_MODAL('upload', {
        contactId,
        folderK: 'f_identity',
        subName: 'Identity and Passaport',
        passportUpload: true,
        onUploaded: async (file) => {
          const url = (file && (file.webViewLink || file.webContentLink || file.url)) || '';
          if (url && window.YEYE_BACKEND && window.YEYE_BACKEND.updateContactProfile) {
            try {
              await window.YEYE_BACKEND.updateContactProfile({
                contactId,
                customFields: [{
                  id: NUDGE_PASSPORT_UPLOAD_FIELD_ID,
                  key: NUDGE_PASSPORT_UPLOAD_FIELD_KEY,
                  value: url,
                }],
              });
              if (window.YEYE_TOAST) window.YEYE_TOAST(t('nudge.passport.saved'));
            } catch (err) {
              console.warn('Passport nudge → GHL field write failed', err);
            }
          }
        },
      });
    } else {
      window.YEYE_GO('documents');
    }
  };

  if (excludedPage || !showProfile || blankProfile) return null;

  return (
    <>
      <aside className="onboarding-nudges" aria-label={t('nudge.regionLabel')}>
        {!blankProfile && showProfile && (
          <OnboardingNudgeCard
            kind="profile"
            icon="clipboard-list"
            title={t('nudge.profile.title')}
            sub={t('nudge.profile.sub').replace('{count}', profile.missing)}
            cta={t('nudge.profile.cta')}
            onAction={() => setWizardOpen(true)}
            onDismiss={() => setProfileDismissed(true)}
          />
        )}
      </aside>
      {wizardOpen && (
        <ProfileWizard
          contact={contact}
          onClose={() => setWizardOpen(false)}
          onSaved={() => setWizardOpen(false)}
        />
      )}
    </>
  );
}

window.OnboardingNudges = OnboardingNudges;
