// OnboardingWizard — 3-step first-visit onboarding
// Step 1: Strategy selection, Step 2: Financial params, Step 3: Recap

const { useState: useOW, useEffect: useEOW } = React;

// ---- SVG Icons inline (Lucide 24x24, stroke-width 1.5) ----
const LUCIDE_ICONS = {
  coins: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="6"/><path d="M18.09 10.37A6 6 0 1 1 10.34 18"/><path d="M7 6h1v4"/><path d="m16.71 13.88.7.71-2.82 2.82"/></svg>',
  home: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>',
  trendingUp: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>',
  wrench: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>',
  recycle: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 19H4.815a1.83 1.83 0 0 1-1.57-.881 1.785 1.785 0 0 1-.004-1.784L7.196 9.5"/><path d="M11 19h8.203a1.83 1.83 0 0 0 1.556-.89 1.784 1.784 0 0 0 0-1.775l-1.226-2.12"/><path d="m14 16-3 3 3 3"/><path d="M8.293 13.596 4.196 5.5"/><path d="m12.5 2-2 4 4 2"/><path d="M14.5 11.5 9.5 9.5"/></svg>',
  graduationCap: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 10v6M2 10l10-5 10 5-10 5z"/><path d="M6 12v5c3 3 9 3 12 0v-5"/></svg>',
  check: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',
  arrowRight: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>',
  arrowLeft: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5"/><path d="m12 19-7-7 7-7"/></svg>',
  user: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>',
  percent: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="5" x2="5" y2="19"/><circle cx="6.5" cy="6.5" r="2.5"/><circle cx="17.5" cy="17.5" r="2.5"/></svg>',
  building: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect width="16" height="20" x="4" y="2" rx="2" ry="2"/><path d="M9 22v-4h6v4"/><path d="M8 6h.01M16 6h.01M12 6h.01M12 10h.01M8 10h.01M16 10h.01M12 14h.01M8 14h.01M16 14h.01"/></svg>',
  creditCard: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="14" x="2" y="5" rx="2"/><line x1="2" y1="10" x2="22" y2="10"/></svg>',
};

// Mapping profile → icon name
const PROFILE_ICONS = {
  cashflow_hunter: 'coins',
  first_buyer: 'home',
  buy_and_hold: 'trendingUp',
  value_add: 'wrench',
  brrrr: 'recycle',
  student_housing: 'graduationCap',
};

// "Convient si..." bullets per profile (FR/EN)
const PROFILE_BULLETS = {
  cashflow_hunter: {
    fr: ['Vous cherchez un flux positif dès le départ', 'Cap rate ≥ 5 % est votre priorité', 'Vous acceptez de gérer activement'],
    en: ['You want positive cash flow from day one', 'Cap rate ≥ 5% is your priority', 'You accept active management'],
  },
  first_buyer: {
    fr: ['Vous souhaitez habiter dans le plex', 'Mise de fonds minimale (10 %)', 'C\'est votre première acquisition'],
    en: ['You want to live in the plex', 'Minimum down payment (10%)', 'This is your first acquisition'],
  },
  buy_and_hold: {
    fr: ['Vision long terme de 15 à 30 ans', 'Vous valorisez l\'appréciation du capital', 'Cashflow modeste acceptable'],
    en: ['Long-term vision of 15–30 years', 'You value capital appreciation', 'Modest cash flow acceptable'],
  },
  value_add: {
    fr: ['Loyers sous le marché à repositionner', 'Vous avez des ressources pour rénover', 'Vous cherchez à créer de la valeur'],
    en: ['Below-market rents to reposition', 'You have renovation resources', 'You aim to create value through upgrades'],
  },
  brrrr: {
    fr: ['Vous voulez recycler votre capital', 'Rénover puis refinancer est votre plan', 'Tolérance au risque plus élevée'],
    en: ['You want to recycle your capital', 'Renovate then refinance is your plan', 'Higher risk tolerance'],
  },
  student_housing: {
    fr: ['Location par chambre vous intéresse', 'Vous acceptez une vacance plus élevée', 'Rendement brut maximal avant tout'],
    en: ['Room-by-room rental appeals to you', 'You accept higher vacancy', 'Maximum gross yield is your goal'],
  },
};

// Labels for the PROFILE_UI_CONFIG (same as index.jsx, used internally)
const OW_PROFILE_CONFIG = {
  cashflow_hunter: { labelFr: 'Rendement',  labelEn: 'Cash Flow',  descFr: 'Cap rate & flux positif',    descEn: 'Cap rate & positive cash flow' },
  first_buyer:     { labelFr: '1er achat',  labelEn: 'First Buy',  descFr: 'Plex avec occupation',       descEn: 'Owner-occupant plex' },
  buy_and_hold:    { labelFr: 'Long terme', labelEn: 'Hold',       descFr: 'Patrimoine 15–30 ans',       descEn: '15–30 yr wealth build' },
  value_add:       { labelFr: 'Value add',  labelEn: 'Value Add',  descFr: 'Loyers sous le marché',      descEn: 'Below-market rents' },
  brrrr:           { labelFr: 'BRRRR',      labelEn: 'BRRRR',      descFr: 'Refinancement après rénov.', descEn: 'Renovate & refinance' },
  student_housing: { labelFr: 'Étudiant',   labelEn: 'Student',    descFr: 'Par chambre, haute densité', descEn: 'Room-by-room rental' },
};

function LucideIcon({ name, size = 24 }) {
  const svg = LUCIDE_ICONS[name];
  if (!svg) return null;
  return (
    <span
      className="lucide-icon"
      style={{ '--icon-size': size + 'px' }}
      dangerouslySetInnerHTML={{ __html: window.DOMPurify ? window.DOMPurify.sanitize(svg, { USE_PROFILES: { svg: true, html: true } }) : svg }} // safe: hardcoded Lucide icon
    />
  );
}

// ---- Step 1: Strategy Selection ----
function StepStrategy({ lang, selectedProfile, onSelect, onContinue }) {
  const t = window.I18N[lang] || window.I18N.fr;
  const FR = lang !== 'en';

  return (
    <div className="onboarding-step">
      <div className="onboarding-step-content">
        <h1 className="onboarding-title">
          {t.onboarding_step1_title}
        </h1>
        <p className="onboarding-subtitle">
          {t.onboarding_step1_subtitle}
        </p>
        <div className="onboarding-strategy-grid">
          {Object.keys(OW_PROFILE_CONFIG).map(id => {
            const cfg = OW_PROFILE_CONFIG[id];
            const label = FR ? cfg.labelFr : cfg.labelEn;
            const desc = FR ? cfg.descFr : cfg.descEn;
            const bullets = FR ? PROFILE_BULLETS[id].fr : PROFILE_BULLETS[id].en;
            const iconName = PROFILE_ICONS[id];
            const isSelected = selectedProfile === id;
            return (
              <button
                key={id}
                className={`onboarding-strategy-card ${isSelected ? 'selected' : ''}`}
                onClick={() => onSelect(id)}
                type="button"
              >
                {isSelected && (
                  <span className="onboarding-check-mark">
                    <LucideIcon name="check" size={16} />
                  </span>
                )}
                <span className="onboarding-card-icon">
                  <LucideIcon name={iconName} size={40} />
                </span>
                <span className="onboarding-card-title">{label}</span>
                <span className="onboarding-card-desc">{desc}</span>
                <ul className="onboarding-card-bullets">
                  {bullets.map((b, i) => (
                    <li key={i}>{b}</li>
                  ))}
                </ul>
              </button>
            );
          })}
        </div>
      </div>
      <div className="onboarding-actions">
        <button
          className="btn onboarding-btn-primary"
          disabled={!selectedProfile}
          onClick={onContinue}
          type="button"
        >
          {t.onboarding_continue}
        </button>
      </div>
    </div>
  );
}

// ---- Step 2: Financial Parameters ----
function StepFinancials({ lang, localProfile, setLocalProfile, onBack, onNext, onSkip }) {
  const t = window.I18N[lang] || window.I18N.fr;
  const FR = lang !== 'en';

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

  function SliderField({ label, value, min, max, step, display, onChange }) {
    return (
      <div className="onboarding-field">
        <div className="onboarding-field-header">
          <span className="onboarding-field-label">{label}</span>
          <span className="onboarding-field-value">{display}</span>
        </div>
        <input
          type="range" min={min} max={max} step={step}
          value={value}
          onChange={e => onChange(+e.target.value)}
          className="onboarding-slider"
        />
      </div>
    );
  }

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

  function SelectField({ label, value, options, onChange }) {
    return (
      <div className="onboarding-field">
        <div className="onboarding-field-header">
          <span className="onboarding-field-label">{label}</span>
        </div>
        <div className="upm-chips" style={{ marginTop: 4 }}>
          {options.map(o => (
            <button
              key={o.value}
              type="button"
              className={`upm-chip ${value === o.value ? 'active' : ''}`}
              onClick={() => onChange(o.value)}
            >
              {o.label}
            </button>
          ))}
        </div>
      </div>
    );
  }

  const financingSourceOpts = [
    { value: 'bank', label: FR ? 'Banque' : 'Bank' },
    { value: 'mortgage_broker', label: FR ? 'Courtier' : 'Broker' },
    { value: 'private', label: FR ? 'Privé' : 'Private' },
  ];

  const amortOpts = [
    { value: 15, label: `15 ${FR ? 'ans' : 'yr'}` },
    { value: 20, label: `20 ${FR ? 'ans' : 'yr'}` },
    { value: 25, label: `25 ${FR ? 'ans' : 'yr'}` },
  ];

  return (
    <div className="onboarding-step">
      <div className="onboarding-step-content">
        <button className="onboarding-back-btn" onClick={onBack} type="button">
          <LucideIcon name="arrowLeft" size={16} />
          {t.onboarding_back}
        </button>
        <h1 className="onboarding-title" style={{ marginTop: 8 }}>
          {t.onboarding_step2_title}
        </h1>
        <div className="onboarding-financial-grid">
          {/* Column 1: Financing */}
          <div className="onboarding-financial-col">
            <h3 className="onboarding-col-title">{FR ? 'Financement' : 'Financing'}</h3>

            <SliderField
              label={FR ? 'Mise de fonds' : 'Down payment'}
              value={Math.round(localProfile.downPaymentPct * 100)}
              min={10} max={35} step={1}
              display={`${Math.round(localProfile.downPaymentPct * 100)} %`}
              onChange={v => set('downPaymentPct', v / 100)}
            />

            <SliderField
              label={FR ? 'Taux hypothécaire' : 'Mortgage rate'}
              value={+(localProfile.mortgageRate * 100).toFixed(2)}
              min={3.5} max={9} step={0.05}
              display={`${(localProfile.mortgageRate * 100).toFixed(2)} %`}
              onChange={v => set('mortgageRate', v / 100)}
            />

            <SelectField
              label={FR ? 'Amortissement' : 'Amortization'}
              value={localProfile.amortizationYears}
              options={amortOpts}
              onChange={v => set('amortizationYears', v)}
            />

            <SelectField
              label={FR ? 'Source de financement' : 'Financing source'}
              value={localProfile.financingSource}
              options={financingSourceOpts}
              onChange={v => set('financingSource', v)}
            />

            <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 6 }}>
              <ToggleField label="SCHL" value={localProfile.isSCHL} onChange={v => set('isSCHL', v)} />
              <ToggleField label={FR ? 'Refinancement' : 'Refinancing'} value={localProfile.isRefinancing} onChange={v => set('isRefinancing', v)} />
              <ToggleField label={FR ? 'Société / Compagnie' : 'Corporation'} value={localProfile.isCompany} onChange={v => set('isCompany', v)} />
            </div>
          </div>

          {/* Column 2: Assumptions */}
          <div className="onboarding-financial-col">
            <h3 className="onboarding-col-title">{FR ? 'Hypothèses' : 'Assumptions'}</h3>

            <SliderField
              label={FR ? 'Taux marginal' : 'Marginal tax rate'}
              value={Math.round(localProfile.marginalTaxRate * 100)}
              min={0} max={54} step={1}
              display={`${Math.round(localProfile.marginalTaxRate * 100)} %`}
              onChange={v => set('marginalTaxRate', v / 100)}
            />

            <SliderField
              label={FR ? 'Appréciation annuelle' : 'Annual appreciation'}
              value={+(localProfile.appreciationRate * 100).toFixed(1)}
              min={1} max={7} step={0.1}
              display={`${(localProfile.appreciationRate * 100).toFixed(1)} %`}
              onChange={v => set('appreciationRate', v / 100)}
            />

            <SliderField
              label={FR ? 'Croissance des loyers' : 'Rent growth / yr'}
              value={+(localProfile.rentGrowthRate * 100).toFixed(1)}
              min={0} max={6} step={0.1}
              display={`${(localProfile.rentGrowthRate * 100).toFixed(1)} %`}
              onChange={v => set('rentGrowthRate', v / 100)}
            />

            <SliderField
              label={FR ? 'Frais de gestion' : 'Management fee'}
              value={Math.round(localProfile.managementPct * 100)}
              min={3} max={15} step={1}
              display={`${Math.round(localProfile.managementPct * 100)} %`}
              onChange={v => set('managementPct', v / 100)}
            />

            <SliderField
              label={FR ? 'Vacance locative' : 'Vacancy rate'}
              value={Math.round(localProfile.vacancyPct * 100)}
              min={2} max={15} step={1}
              display={`${Math.round(localProfile.vacancyPct * 100)} %`}
              onChange={v => set('vacancyPct', v / 100)}
            />

            <SliderField
              label={FR ? 'TGA secteur' : 'Sector cap rate (TGA)'}
              value={+(localProfile.tga * 100).toFixed(2)}
              min={3} max={9} step={0.05}
              display={`${(localProfile.tga * 100).toFixed(2)} %`}
              onChange={v => set('tga', v / 100)}
            />
          </div>
        </div>
      </div>
      <div className="onboarding-actions">
        <button
          className="onboarding-skip-link"
          onClick={onSkip}
          type="button"
        >
          {t.onboarding_keep_defaults}
        </button>
        <button
          className="btn onboarding-btn-primary"
          onClick={onNext}
          type="button"
        >
          {t.onboarding_continue}
        </button>
      </div>
    </div>
  );
}

// ---- Step 3: Recap ----
function StepRecap({ lang, selectedProfile, localProfile, onComplete, onEdit }) {
  const t = window.I18N[lang] || window.I18N.fr;
  const FR = lang !== 'en';

  const cfg = OW_PROFILE_CONFIG[selectedProfile];
  const strategyLabel = cfg ? (FR ? cfg.labelFr : cfg.labelEn) : selectedProfile;

  const financingSourceLabel = {
    bank: FR ? 'Banque' : 'Bank',
    mortgage_broker: FR ? 'Courtier hypothécaire' : 'Mortgage broker',
    private: FR ? 'Privé' : 'Private',
  }[localProfile.financingSource] || localProfile.financingSource;

  const downPct = Math.round(localProfile.downPaymentPct * 100);
  const ratePct = (localProfile.mortgageRate * 100).toFixed(2);

  const summary = FR
    ? `Vous êtes investisseur **${strategyLabel}** avec **${downPct}%** de mise de fonds, taux **${ratePct}%**, financement **${financingSourceLabel}**.`
    : `You are a **${strategyLabel}** investor with **${downPct}%** down, **${ratePct}%** rate, **${financingSourceLabel}** financing.`;

  // Bold markdown helper
  function BoldMd({ text }) {
    const parts = text.split(/\*\*(.*?)\*\*/g);
    return (
      <span>
        {parts.map((p, i) => i % 2 === 1 ? <strong key={i}>{p}</strong> : p)}
      </span>
    );
  }

  const keyParams = [
    { icon: 'percent', label: FR ? 'Mise de fonds' : 'Down payment', value: `${downPct}%` },
    { icon: 'creditCard', label: FR ? 'Taux hypothécaire' : 'Mortgage rate', value: `${ratePct}%` },
    { icon: 'building', label: FR ? 'Amortissement' : 'Amortization', value: `${localProfile.amortizationYears} ${FR ? 'ans' : 'yrs'}` },
    { icon: 'percent', label: FR ? 'Vacance' : 'Vacancy', value: `${Math.round(localProfile.vacancyPct * 100)}%` },
    { icon: 'coins', label: FR ? 'Gestion' : 'Management', value: `${Math.round(localProfile.managementPct * 100)}%` },
  ];

  return (
    <div className="onboarding-step">
      <div className="onboarding-step-content">
        <div className="onboarding-recap-icon">
          <LucideIcon name={PROFILE_ICONS[selectedProfile] || 'user'} size={48} />
        </div>
        <h1 className="onboarding-title">{t.onboarding_step3_title}</h1>
        <p className="onboarding-summary-text">
          <BoldMd text={summary} />
        </p>

        <div className="onboarding-recap-params">
          {keyParams.map((p, i) => (
            <div key={i} className="onboarding-recap-param">
              <span className="onboarding-recap-param-icon">
                <LucideIcon name={p.icon} size={18} />
              </span>
              <span className="onboarding-recap-param-label">{p.label}</span>
              <span className="onboarding-recap-param-value">{p.value}</span>
            </div>
          ))}
        </div>
      </div>
      <div className="onboarding-actions">
        <button
          className="onboarding-skip-link"
          onClick={onEdit}
          type="button"
        >
          {t.onboarding_modify}
        </button>
        <button
          className="btn onboarding-btn-primary"
          onClick={onComplete}
          type="button"
        >
          {t.onboarding_complete_cta}
        </button>
      </div>
    </div>
  );
}

// ---- Progress indicator ----
function ProgressBar({ step, total }) {
  return (
    <div className="onboarding-progress" aria-label={`Step ${step} of ${total}`}>
      {Array.from({ length: total }, (_, i) => (
        <div
          key={i}
          className={`onboarding-progress-dot ${i + 1 === step ? 'active' : ''} ${i + 1 < step ? 'done' : ''}`}
        />
      ))}
    </div>
  );
}

// ---- Main OnboardingWizard ----
function OnboardingWizard({ lang, onComplete }) {
  const [currentStep, setCurrentStep] = useOW(1);
  const [selectedProfile, setSelectedProfile] = useOW(null);
  const [localProfile, setLocalProfile] = useOW(() => ({ ...(window.DEFAULT_USER_PROFILE || {}) }));

  // When profile is selected, pre-fill financial defaults
  const handleSelectProfile = (id) => {
    setSelectedProfile(id);
  };

  const handleContinueStep1 = () => {
    if (!selectedProfile) return;
    const defaults = window.PROFILE_FINANCIAL_DEFAULTS && window.PROFILE_FINANCIAL_DEFAULTS[selectedProfile];
    const base = window.DEFAULT_USER_PROFILE || {};
    setLocalProfile({ ...base, ...(defaults || {}) });
    setCurrentStep(2);
  };

  const handleContinueStep2 = () => {
    setCurrentStep(3);
  };

  const handleSkipStep2 = () => {
    // Keep defaults, go to complete
    const finalProfile = { ...localProfile, strategyId: selectedProfile };
    onComplete(finalProfile);
  };

  const handleComplete = () => {
    const finalProfile = { ...localProfile, strategyId: selectedProfile };
    onComplete(finalProfile);
  };

  return (
    <div className="onboarding-overlay">
      <div className="onboarding-card">
        <div className="onboarding-header">
          <div className="onboarding-brand">
            <span className="brand-mark" style={{ fontSize: 18, width: 28, height: 28 }}>V</span>
            <span style={{ fontWeight: 600, fontSize: 16, color: 'var(--ink-1)' }}>Vestora</span>
          </div>
          <ProgressBar step={currentStep} total={3} />
          <div className="onboarding-step-label">
            {currentStep} / 3
          </div>
        </div>

        {currentStep === 1 && (
          <StepStrategy
            lang={lang}
            selectedProfile={selectedProfile}
            onSelect={handleSelectProfile}
            onContinue={handleContinueStep1}
          />
        )}

        {currentStep === 2 && (
          <StepFinancials
            lang={lang}
            localProfile={localProfile}
            setLocalProfile={setLocalProfile}
            onBack={() => setCurrentStep(1)}
            onNext={handleContinueStep2}
            onSkip={handleSkipStep2}
          />
        )}

        {currentStep === 3 && (
          <StepRecap
            lang={lang}
            selectedProfile={selectedProfile}
            localProfile={localProfile}
            onComplete={handleComplete}
            onEdit={() => setCurrentStep(1)}
          />
        )}
      </div>
    </div>
  );
}

// Expose globally
window.OnboardingWizard = OnboardingWizard;
window.LUCIDE_ICONS = LUCIDE_ICONS;
window.PROFILE_ICONS = PROFILE_ICONS;
