// UserProfileModal — configuration du profil investisseur, persisté dans localStorage

const { useState: useSPM, useEffect: useEPM, useCallback: useCBPM } = React;

const PROFILE_KEY = 'vestora_user_profile';

const DEFAULT_USER_PROFILE = {
  downPaymentPct: 0.20,
  mortgageRate: 0.055,
  amortizationYears: 25,
  isSCHL: false,
  isRefinancing: false,
  isCompany: false,
  financingSource: 'bank',
  marginalTaxRate: 0.40,
  appreciationRate: 0.03,
  rentGrowthRate: 0.03,
  managementPct: 0.08,
  vacancyPct: 0.05,
  tga: 0.055,
};

function loadProfile() {
  try {
    const raw = localStorage.getItem(PROFILE_KEY);
    if (raw) return { ...DEFAULT_USER_PROFILE, ...JSON.parse(raw) };
  } catch (e) {}
  return { ...DEFAULT_USER_PROFILE };
}

function saveProfile(p) {
  try { localStorage.setItem(PROFILE_KEY, JSON.stringify(p)); } catch (e) {}
  window.userProfile = p;
}

// Expose globalement
window.userProfile = loadProfile();

function UserProfileModal({ open, onClose, lang, onStrategyChange }) {
  const t = window.I18N[lang] || window.I18N.fr;
  const [profile, setProfile] = useSPM(() => loadProfile());
  const [saved, setSaved] = useSPM(false);

  useEPM(() => {
    if (open) setProfile(loadProfile());
  }, [open]);

  const set = (key, val) => setProfile(p => ({ ...p, [key]: val }));

  const handleSave = () => {
    saveProfile(profile);
    setSaved(true);
    setTimeout(() => { setSaved(false); onClose(); }, 700);
  };

  const handleReset = () => setProfile({ ...DEFAULT_USER_PROFILE });

  const handleExport = () => {
    const blob = new Blob([JSON.stringify(profile, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = 'vestora-profile.json'; a.click();
    URL.revokeObjectURL(url);
  };

  const handleImport = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      try {
        const parsed = JSON.parse(ev.target.result);
        setProfile({ ...DEFAULT_USER_PROFILE, ...parsed });
      } catch {}
    };
    reader.readAsText(file);
    e.target.value = '';
  };

  if (!open) return null;

  const FR = lang !== 'en';

  function SliderRow({ label, value, min, max, step, display, onChg, note }) {
    return (
      <div className="upm-row">
        <div className="upm-row-top">
          <label className="upm-label">{label}</label>
          <span className="upm-display">{display}</span>
        </div>
        {note && <div className="upm-note">{note}</div>}
        <input type="range" min={min} max={max} step={step}
          value={value} onChange={e => onChg(+e.target.value)}
          className="upm-slider"/>
        <div className="upm-range-labels">
          <span>{min}</span><span>{max}</span>
        </div>
      </div>
    );
  }

  function ToggleRow({ label, value, onChg }) {
    return (
      <label className="upm-toggle-row">
        <span className="upm-label">{label}</span>
        <button
          className={`upm-toggle ${value ? 'on' : ''}`}
          onClick={() => onChg(!value)}
          type="button"
        >
          <span className="upm-toggle-thumb"/>
        </button>
      </label>
    );
  }

  return (
    <div className="upm-backdrop" onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="upm-panel">
        <div className="upm-header">
          <h2 className="upm-title">
            {FR ? 'Mon profil investisseur' : 'My investor profile'}
          </h2>
          <button className="upm-close" onClick={onClose} aria-label={t.close}>
            <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.5" fill="none">
              <path d="M2 2l10 10M12 2L2 12"/>
            </svg>
          </button>
        </div>

        <div className="upm-body">

          {/* Stratégie investisseur */}
          {typeof window.PROFILE_UI_CONFIG !== 'undefined' && (
            <section className="upm-section">
              <h3 className="upm-section-title">
                {FR ? 'Stratégie d\'investissement' : 'Investment strategy'}
              </h3>
              <div className="upm-strategy-grid">
                {window.PROFILE_UI_CONFIG.map(p => {
                  const isSelected = profile.strategyId === p.id;
                  return (
                    <button
                      key={p.id}
                      type="button"
                      className={`upm-strategy-btn ${isSelected ? 'selected' : ''}`}
                      onClick={() => {
                        const defaults = window.PROFILE_FINANCIAL_DEFAULTS && window.PROFILE_FINANCIAL_DEFAULTS[p.id];
                        setProfile(prev => ({ ...prev, strategyId: p.id, ...(defaults || {}) }));
                        if (onStrategyChange) onStrategyChange(p.id);
                      }}
                      title={FR ? p.desc_fr : p.desc_en}
                    >
                      {p.icon} {FR ? p.fr : p.en}
                    </button>
                  );
                })}
              </div>
            </section>
          )}

          {/* Financement */}
          <section className="upm-section">
            <h3 className="upm-section-title">
              {FR ? 'Financement' : 'Financing'}
            </h3>
            <SliderRow
              label={FR ? 'Mise de fonds' : 'Down payment'}
              value={Math.round(profile.downPaymentPct * 100)}
              min={10} max={35} step={1}
              display={`${Math.round(profile.downPaymentPct * 100)} %`}
              onChg={v => set('downPaymentPct', v / 100)}
            />
            <SliderRow
              label={FR ? 'Taux hypothécaire' : 'Mortgage rate'}
              value={+(profile.mortgageRate * 100).toFixed(2)}
              min={3.5} max={9} step={0.05}
              display={`${(profile.mortgageRate * 100).toFixed(2)} %`}
              onChg={v => set('mortgageRate', v / 100)}
            />
            <div className="upm-row">
              <div className="upm-row-top">
                <label className="upm-label">{FR ? 'Amortissement' : 'Amortization'}</label>
                <span className="upm-display">{profile.amortizationYears} {FR ? 'ans' : 'yrs'}</span>
              </div>
              <div className="upm-chips">
                {[15, 20, 25].map(y => (
                  <button key={y}
                    className={`upm-chip ${profile.amortizationYears === y ? 'active' : ''}`}
                    onClick={() => set('amortizationYears', y)}
                    type="button"
                  >{y} {FR ? 'ans' : 'yr'}</button>
                ))}
              </div>
            </div>
            <div className="upm-row">
              <div className="upm-row-top">
                <label className="upm-label">{FR ? 'Source de financement' : 'Financing source'}</label>
              </div>
              <div className="upm-chips">
                {[
                  { key: 'bank', label: FR ? 'Banque' : 'Bank' },
                  { key: 'mortgage_broker', label: FR ? 'Courtier' : 'Broker' },
                  { key: 'private', label: FR ? 'Privé' : 'Private' },
                ].map(({ key, label }) => (
                  <button key={key}
                    className={`upm-chip ${profile.financingSource === key ? 'active' : ''}`}
                    onClick={() => set('financingSource', key)}
                    type="button"
                  >{label}</button>
                ))}
              </div>
            </div>
            <div className="upm-toggles">
              <ToggleRow label="SCHL" value={profile.isSCHL} onChg={v => set('isSCHL', v)}/>
              <ToggleRow
                label={FR ? 'Refinancement' : 'Refinancing'}
                value={profile.isRefinancing}
                onChg={v => set('isRefinancing', v)}
              />
              <ToggleRow
                label={FR ? 'Société / Compagnie' : 'Corporation'}
                value={profile.isCompany}
                onChg={v => set('isCompany', v)}
              />
            </div>
          </section>

          {/* Fiscalité */}
          <section className="upm-section">
            <h3 className="upm-section-title">
              {FR ? 'Fiscalité & projections' : 'Tax & projections'}
            </h3>
            <SliderRow
              label={FR ? 'Taux marginal d\'imposition' : 'Marginal tax rate'}
              value={Math.round(profile.marginalTaxRate * 100)}
              min={0} max={54} step={1}
              display={`${Math.round(profile.marginalTaxRate * 100)} %`}
              onChg={v => set('marginalTaxRate', v / 100)}
            />
            <SliderRow
              label={FR ? 'Appréciation annuelle' : 'Annual appreciation'}
              value={+(profile.appreciationRate * 100).toFixed(1)}
              min={1} max={7} step={0.1}
              display={`${(profile.appreciationRate * 100).toFixed(1)} %`}
              onChg={v => set('appreciationRate', v / 100)}
            />
            <SliderRow
              label={FR ? 'Croissance des loyers / an' : 'Rent growth / yr'}
              value={+(profile.rentGrowthRate * 100).toFixed(1)}
              min={0} max={6} step={0.1}
              display={`${(profile.rentGrowthRate * 100).toFixed(1)} %`}
              onChg={v => set('rentGrowthRate', v / 100)}
            />
          </section>

          {/* Exploitation */}
          <section className="upm-section">
            <h3 className="upm-section-title">
              {FR ? 'Exploitation' : 'Operations'}
            </h3>
            <SliderRow
              label={FR ? 'Gestion / administration' : 'Management fee'}
              value={Math.round(profile.managementPct * 100)}
              min={3} max={15} step={1}
              display={`${Math.round(profile.managementPct * 100)} %`}
              note={FR ? 'En % du revenu brut effectif' : '% of effective gross income'}
              onChg={v => set('managementPct', v / 100)}
            />
            <SliderRow
              label={FR ? 'Vacance locative' : 'Vacancy rate'}
              value={Math.round(profile.vacancyPct * 100)}
              min={2} max={15} step={1}
              display={`${Math.round(profile.vacancyPct * 100)} %`}
              onChg={v => set('vacancyPct', v / 100)}
            />
          </section>

          {/* Marché */}
          <section className="upm-section">
            <h3 className="upm-section-title">
              {FR ? 'Paramètres marché' : 'Market parameters'}
            </h3>
            <SliderRow
              label={FR ? 'TGA secteur (Taux global actuariel)' : 'Sector cap rate (TGA)'}
              value={+(profile.tga * 100).toFixed(2)}
              min={3} max={9} step={0.05}
              display={`${(profile.tga * 100).toFixed(2)} %`}
              note={FR ? 'Utilisé pour la valeur marchande TGA' : 'Used for TGA market value'}
              onChg={v => set('tga', v / 100)}
            />
          </section>

        </div>

        <div className="upm-footer">
          <div className="upm-footer-left">
            <button className="btn btn-ghost upm-btn-sm" onClick={handleReset} type="button">
              {FR ? 'Défauts' : 'Reset'}
            </button>
            <button className="btn btn-ghost upm-btn-sm" onClick={handleExport} type="button">
              {FR ? 'Export JSON' : 'Export JSON'}
            </button>
            <label className="btn btn-ghost upm-btn-sm upm-import-label">
              {FR ? 'Import JSON' : 'Import JSON'}
              <input type="file" accept=".json" onChange={handleImport} style={{ display: 'none' }}/>
            </label>
          </div>
          <button className={`btn upm-btn-save ${saved ? 'saved' : ''}`} onClick={handleSave} type="button">
            {saved ? (FR ? 'Sauvegardé ✓' : 'Saved ✓') : (FR ? 'Sauvegarder' : 'Save')}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { UserProfileModal, loadUserProfile: loadProfile, saveUserProfile: saveProfile, DEFAULT_USER_PROFILE });
