/* ------------------------------------------------------------------ *
 *  Modules optionnels — temps fauteuil + financement (LOA / crédit-bail)
 * ------------------------------------------------------------------ */

function ModuleTempsFauteuil({ enabled, onToggle, params, setParams, rows }) {
  const { NumberInput, Icon } = window;
  const { t, fmt, currencySymbol } = useLang();

  const creneauxMois = rows.reduce((sum, r) => {
    if (!r.actif || r.machine !== 'midas') return sum;
    return sum + (r.values.volume || 0);
  }, 0);

  const potentielMois = creneauxMois * (params.tauxRemplissage / 100) * params.tarifActe;
  const provMois      = (params.economieProvisoireParCas || 0) * (params.casProvisoiresMois || 0);
  const totalMois     = potentielMois + provMois;
  const totalAn       = totalMois * 12;
  const hasMidas      = creneauxMois > 0;

  return (
    <div className={`rounded-2xl border shadow-card transition ${enabled ? 'bg-white border-ink-200' : 'bg-ink-50/50 border-ink-100'}`}>
      <div className="px-5 py-4 flex items-start justify-between gap-3 border-b border-ink-100">
        <div className="flex items-start gap-3">
          <div className={`w-9 h-9 rounded-xl grid place-items-center ${enabled ? 'bg-brand-500 text-white' : 'bg-ink-100 text-ink-400'}`}>
            <Icon.chair/>
          </div>
          <div>
            <div className="flex items-center gap-2">
              <h3 className="text-[14px] font-semibold text-ink-900">{t('mod.temps.title')}</h3>
              <span className="text-[10.5px] font-medium px-1.5 py-0.5 rounded-md bg-ink-100 text-ink-500">{t('mod.badge')}</span>
            </div>
            <p className="text-[12px] text-ink-500 mt-0.5 max-w-xl">{t('mod.temps.desc')}</p>
          </div>
        </div>
        <Toggle on={enabled} onChange={onToggle}/>
      </div>

      {enabled && (
        <div className="p-5 fade-up space-y-4">

          {/* Hero auto-calculé */}
          <div className={`rounded-xl px-4 py-3 flex items-center gap-4 border ${hasMidas ? 'bg-brand-50/60 border-brand-200' : 'bg-ink-50 border-ink-200'}`}>
            <div className={`w-11 h-11 rounded-full grid place-items-center shrink-0 text-[20px] ${hasMidas ? 'bg-brand-100 text-brand-600' : 'bg-ink-100 text-ink-400'}`}>
              🪑
            </div>
            <div className="flex-1 min-w-0">
              {hasMidas ? (
                <>
                  <div className="flex items-baseline gap-2">
                    <span className="text-[28px] font-semibold tnum text-brand-700 leading-none">{creneauxMois}</span>
                    <span className="text-[13px] text-brand-600">{t('mod.temps.creneaux')}</span>
                  </div>
                  <div className="text-[11.5px] text-ink-500 mt-0.5">{t('mod.temps.creneaux.sub', creneauxMois)}</div>
                </>
              ) : (
                <p className="text-[12.5px] text-ink-400 italic">{t('mod.temps.nomidas')}</p>
              )}
            </div>
          </div>

          {/* 2 inputs */}
          <div className="grid grid-cols-2 gap-4">
            <Field label={t('mod.temps.tarif')} hint={t('mod.temps.tarif.hint')}>
              <NumberInput value={params.tarifActe}
                           onChange={v => setParams({ ...params, tarifActe: v })}
                           suffix={currencySymbol}/>
            </Field>
            <Field label={t('mod.temps.taux')} hint={t('mod.temps.taux.hint')}>
              <NumberInput value={params.tauxRemplissage}
                           onChange={v => setParams({ ...params, tauxRemplissage: Math.min(100, Math.max(0, v)) })}
                           suffix="%"/>
            </Field>
          </div>

          {/* Équation résultat */}
          {hasMidas && (
            <div className="rounded-xl bg-ink-50 px-4 py-2.5 text-[12.5px] text-ink-600 flex flex-wrap items-center gap-1.5">
              <span className="tnum font-semibold text-ink-900">{creneauxMois}</span>
              <span className="text-ink-400">×</span>
              <span className="tnum font-semibold text-ink-900">{params.tauxRemplissage} %</span>
              <span className="text-ink-400">×</span>
              <span className="tnum font-semibold text-ink-900">{fmt.EUR(params.tarifActe)}</span>
              <span className="text-ink-400">=</span>
              <span className="tnum font-semibold text-brand-700">{fmt.EUR(potentielMois)}</span>
              <span className="text-ink-400">{t('mod.temps.potentiel.mois')}</span>
            </div>
          )}

          {/* Provisoires — section secondaire repliable */}
          <details className="group">
            <summary className="cursor-pointer select-none list-none flex items-center gap-1.5 text-[11.5px] text-ink-400 hover:text-ink-600 transition w-fit">
              <svg className="group-open:rotate-90 transition-transform shrink-0" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M9 18l6-6-6-6"/>
              </svg>
              {t('mod.temps.prov')}
            </summary>
            <div className="mt-3 grid grid-cols-2 gap-4">
              <Field label={t('mod.temps.cas')} hint={t('mod.temps.cas.hint')}>
                <NumberInput value={params.casProvisoiresMois}
                             onChange={v => setParams({ ...params, casProvisoiresMois: v })}
                             suffix="cas"/>
              </Field>
              <Field label={t('mod.temps.eco')} hint={t('mod.temps.eco.hint')}>
                <NumberInput value={params.economieProvisoireParCas}
                             onChange={v => setParams({ ...params, economieProvisoireParCas: v })}
                             suffix={currencySymbol}/>
              </Field>
            </div>
          </details>

          {/* Total annuel */}
          <div className="flex items-center justify-between rounded-xl bg-gradient-to-r from-brand-50 to-brand-100/60 px-4 py-3 border border-brand-200">
            <div>
              <div className="text-[12px] text-brand-700 font-medium uppercase tracking-wider">{t('mod.temps.potentiel')}</div>
              <div className="text-[11.5px] text-ink-500 max-w-md">{t('mod.temps.potentiel.sub')}</div>
            </div>
            <div className="text-right">
              <div className="text-[26px] font-semibold tnum text-brand-700">{fmt.EUR(totalAn)}</div>
              <div className="text-[11px] text-brand-600">{t('mod.temps.paran')}</div>
            </div>
          </div>

        </div>
      )}
    </div>
  );
}

function ModuleFinancement({ enabled, onToggle, params, setParams, economieMois, prixEcosysteme, className = '' }) {
  const { NumberInput, Icon } = window;
  const { t, fmt, currencySymbol } = useLang();

  const r = (params.tauxAnnuel || 0) > 0 ? params.tauxAnnuel / 100 / 12 : 0;
  const n = params.dureeMois || 0;
  const loyerCalc = n > 0
    ? (r > 0 ? prixEcosysteme * r / (1 - Math.pow(1 + r, -n)) : prixEcosysteme / n)
    : 0;
  const loyer = params.loyerManuel > 0 ? params.loyerManuel : loyerCalc;
  const cashFlowNet = economieMois - loyer;
  const autofinance = cashFlowNet > 0;
  const coutTotal = loyer * n;
  const coutInterets = Math.max(0, coutTotal - prixEcosysteme);

  return (
    <div className={`rounded-2xl border shadow-card transition ${enabled ? 'bg-white border-ink-200' : 'bg-ink-50/50 border-ink-100'} ${className}`}>
      <div className="px-5 py-4 flex items-start justify-between gap-3 border-b border-ink-100">
        <div className="flex items-start gap-3">
          <div className={`w-9 h-9 rounded-xl grid place-items-center ${enabled ? 'bg-brand-500 text-white' : 'bg-ink-100 text-ink-400'}`}>
            <Icon.flow/>
          </div>
          <div>
            <div className="flex items-center gap-2">
              <h3 className="text-[14px] font-semibold text-ink-900">{t('mod.fin.title')}</h3>
              <span className="text-[10.5px] font-medium px-1.5 py-0.5 rounded-md bg-ink-100 text-ink-500">{t('mod.badge')}</span>
            </div>
            <p className="text-[12px] text-ink-500 mt-0.5 max-w-xl"
               dangerouslySetInnerHTML={{ __html: t('mod.fin.desc') }}/>
          </div>
        </div>
        <Toggle on={enabled} onChange={onToggle}/>
      </div>

      {enabled && (
        <div className="p-5 fade-up">
          <div className="grid grid-cols-2 gap-4 mb-5">
            <Field label={t('mod.fin.duree')} hint={t('mod.fin.duree.hint')}>
              <NumberInput value={params.dureeMois}
                           onChange={v => setParams({ ...params, dureeMois: v })}
                           suffix="mois"/>
            </Field>
            <Field label={t('mod.fin.taux')} hint={t('mod.fin.taux.hint')}>
              <NumberInput value={params.tauxAnnuel || undefined}
                           step={0.1}
                           onChange={v => setParams({ ...params, tauxAnnuel: v })}
                           suffix="%"/>
            </Field>
            <Field label={t('mod.fin.auto')} hint={t('mod.fin.auto.hint')}>
              <div className="cell-input text-right tnum text-ink-500" style={{cursor:'default'}}>
                {fmt.EUR(loyerCalc)}
              </div>
            </Field>
            <Field label={t('mod.fin.loyer')} hint={t('mod.fin.loyer.hint')}>
              <NumberInput value={params.loyerManuel || undefined}
                           onChange={v => setParams({ ...params, loyerManuel: v })}
                           suffix={currencySymbol}/>
            </Field>
          </div>

          <div className={`rounded-xl px-4 py-4 border ${autofinance ? 'bg-emerald-50 border-emerald-200' : 'bg-amber-50 border-amber-200'}`}>
            <div className="flex items-start justify-between gap-4">
              <div className="flex-1">
                <div className={`text-[12px] font-medium uppercase tracking-wider ${autofinance ? 'text-emerald-700' : 'text-amber-700'}`}>
                  {t('mod.fin.cashflow')}
                </div>
                <div className={`mt-1 text-[28px] font-semibold tnum ${autofinance ? 'text-emerald-700' : 'text-amber-700'}`}>
                  {fmt.EURc(cashFlowNet)}
                </div>
                <div className="mt-2 text-[12.5px] text-ink-700 max-w-lg"
                     dangerouslySetInnerHTML={{ __html: autofinance
                       ? t('mod.fin.pos', fmt.EUR(cashFlowNet))
                       : t('mod.fin.neg', fmt.EUR(-cashFlowNet)) }}/>
              </div>
              <div className="hidden md:block">
                <div className={`w-12 h-12 rounded-full grid place-items-center ${autofinance ? 'bg-emerald-500 text-white' : 'bg-amber-500 text-white'}`}>
                  {autofinance ? <Icon.check/> : <Icon.warn/>}
                </div>
              </div>
            </div>

            <div className="mt-4 grid grid-cols-3 gap-2 text-[12px]">
              <Mini label={t('mod.fin.mini.eco')}   value={fmt.EUR(economieMois)}   tone="ink"/>
              <Mini label={t('mod.fin.mini.loyer')} value={fmt.EUR(loyer)}          tone="ink"/>
              <Mini label={t('mod.fin.mini.net')}   value={fmt.EURc(cashFlowNet)}   tone={autofinance?'em':'am'}/>
            </div>

            {coutInterets > 0 && (
              <div className="mt-3 pt-3 border-t border-black/8 flex items-center justify-between text-[11.5px] text-ink-500">
                <span>{t('mod.fin.cout.label')}</span>
                <span className="tnum font-medium text-ink-700">{fmt.EUR(coutTotal)}
                  <span className="text-ink-400 font-normal ml-1">({t('mod.fin.cout.interets', fmt.EUR(coutInterets))})</span>
                </span>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

function Field({ label, hint, children }) {
  return (
    <div>
      <label className="block text-[12px] font-medium text-ink-700">{label}</label>
      {hint && <p className="text-[11px] text-ink-400 mb-1">{hint}</p>}
      <div className="bg-ink-50 rounded-lg px-2 py-1.5">
        {children}
      </div>
    </div>
  );
}

function Mini({ label, value, tone }) {
  const tones = { ink: 'bg-white text-ink-900', em: 'bg-white text-emerald-700', am: 'bg-white text-amber-700' };
  return (
    <div className={`rounded-lg px-3 py-2 ${tones[tone]}`}>
      <div className="text-[10.5px] uppercase tracking-wider text-ink-400">{label}</div>
      <div className="tnum font-semibold">{value}</div>
    </div>
  );
}

function Toggle({ on, onChange }) {
  return (
    <button onClick={() => onChange(!on)}
            className={`relative w-11 h-6 rounded-full transition shrink-0 ${on ? 'bg-brand-500' : 'bg-ink-200'}`}
            aria-pressed={on}>
      <span className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${on ? 'translate-x-5' : ''}`}></span>
    </button>
  );
}

function ModuleCamera({ enabled, onToggle, params, setParams, economieMois, prixEcosysteme, className = '' }) {
  const { NumberInput, Icon } = window;
  const { t, fmt, currencySymbol } = useLang();

  const mensualite  = params.mensualiteManuelle || 0;
  const ecoNette    = economieMois - mensualite;
  const moisSans    = economieMois > 0 ? Math.ceil(prixEcosysteme / economieMois) : null;
  const moisAvec    = ecoNette > 0    ? Math.ceil(prixEcosysteme / ecoNette)     : null;
  const delta       = (moisAvec && moisSans) ? moisAvec - moisSans : null;

  return (
    <div className={`rounded-2xl border shadow-card transition ${enabled ? 'bg-white border-ink-200' : 'bg-ink-50/50 border-ink-100'} ${className}`}>
      <div className="px-5 py-4 flex items-start justify-between gap-3 border-b border-ink-100">
        <div className="flex items-start gap-3">
          <div className={`w-9 h-9 rounded-xl grid place-items-center ${enabled ? 'bg-brand-500 text-white' : 'bg-ink-100 text-ink-400'}`}>
            <Icon.camera/>
          </div>
          <div>
            <div className="flex items-center gap-2">
              <h3 className="text-[14px] font-semibold text-ink-900">{t('mod.cam.title')}</h3>
              <span className="text-[10.5px] font-medium px-1.5 py-0.5 rounded-md bg-ink-100 text-ink-500">{t('mod.badge')}</span>
            </div>
            <p className="text-[12px] text-ink-500 mt-0.5 max-w-xl">{t('mod.cam.desc')}</p>
          </div>
        </div>
        <Toggle on={enabled} onChange={onToggle}/>
      </div>

      {enabled && (
        <div className="p-5 fade-up">
          <div className="mb-5">
            <Field label={t('mod.cam.loyer')} hint={t('mod.cam.loyer.hint')}>
              <NumberInput value={params.mensualiteManuelle || undefined}
                           warn={!params.mensualiteManuelle}
                           onChange={v => setParams({ ...params, mensualiteManuelle: v })}
                           suffix={currencySymbol}/>
            </Field>
          </div>

          <div className="rounded-xl bg-ink-50 border border-ink-200 px-4 py-3">
            <div className="text-[11.5px] font-medium text-ink-600 uppercase tracking-wider mb-2">{t('mod.cam.impact')}</div>
            <div className="grid grid-cols-2 gap-2 text-[12px]">
              <Mini label={t('mod.cam.mini.mens')}  value={fmt.EUR(mensualite)}          tone="ink"/>
              <Mini label={t('mod.cam.mini.roi')}   value={moisAvec ? t('synth.gen.roiOk', moisAvec) : t('dash.roi.nd')}
                                                    tone={moisAvec ? 'ink' : 'am'}/>
            </div>
            {delta !== null && delta > 0 && (
              <p className="mt-2 text-[11.5px] text-ink-500">
                {t('mod.cam.impact.delta', delta, moisSans, moisAvec)}
              </p>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ModuleTempsFauteuil, ModuleFinancement, ModuleCamera, Toggle, Field, Mini });
