/* ------------------------------------------------------------------ *
 *  Tableau d'indications éditable
 * ------------------------------------------------------------------ */

function IndicationsTable({ rows, setRows }) {
  const { NumberInput, Icon } = window;
  const { t, fmt, currencySymbol } = useLang();

  function patchRow(id, patch) {
    setRows((rs) => rs.map((r) =>
      r.id === id ? { ...r, ...patch, values: { ...r.values, ...(patch.values || {}) } } : r
    ));
  }
  function setVal(id, key, v) { patchRow(id, { values: { [key]: v } }); }
  function toggle(id) { setRows((rs) => rs.map((r) => r.id === id ? { ...r, actif: !r.actif } : r)); }
  function reset(id) {
    setRows((rs) => rs.map((r) => r.id === id ? {
      ...r, values: { ...r.def, coutMateriau: r.def.coutMateriau ?? 0 }
    } : r));
  }

  return (
    <div className="bg-white rounded-2xl border border-ink-200 shadow-card overflow-hidden fade-up">
      <div className="flex items-center justify-between px-5 py-4 border-b border-ink-100">
        <div>
          <h2 className="text-[15px] font-semibold text-ink-900">{t('table.title')}</h2>
          <p className="text-[12.5px] text-ink-500 mt-0.5">{t('table.sub')}</p>
        </div>
      </div>

      <div className="overflow-x-auto nice-scroll">
        <table className="w-full text-[13px]">
          <thead className="bg-ink-50/60 text-ink-500">
            <tr className="text-left">
              <th className="px-4 py-2.5 font-medium w-8"></th>
              <th className="px-4 py-2.5 font-medium">{t('table.col.indication')}</th>
              <th className="px-3 py-2.5 font-medium text-right">{t('table.col.coutLabo')}</th>
              <th className="px-3 py-2.5 font-medium text-right w-[180px]">{t('table.col.volume')}</th>
              <th className="px-3 py-2.5 font-medium text-right">{t('table.col.materiau')}</th>
              <th className="px-3 py-2.5 font-medium text-right">{t('table.col.design')}</th>
              <th className="px-3 py-2.5 font-medium text-right">{t('table.col.economie')}</th>
              <th className="px-2 py-2.5 font-medium w-8"></th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 && (
              <tr>
                <td colSpan={8} className="px-4 py-10 text-center text-ink-400 text-sm">
                  {t('table.empty')}
                </td>
              </tr>
            )}

            {rows.map((r, idx) => {
              const c = window.calculerLigne(r, 0);
              const matLabel = r.machine === 'midas' ? r._midasMaterialLabel : r.materiauPro2;
              const label = t('cat.' + r.id + '.label');
              const sub   = t('cat.' + r.id + '.sub');

              const prev = rows[idx - 1];
              const showHeader = !prev || prev.machine !== r.machine;

              return (
                <React.Fragment key={r.id}>
                  {showHeader && (
                    <tr className="bg-gradient-to-r from-brand-50/70 via-white to-white">
                      <td colSpan={8} className="px-4 py-2.5">
                        <div className="flex items-center gap-2 text-[11.5px] uppercase tracking-[0.12em] font-semibold text-brand-700">
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                            <path d="M6 9V3h12v6" /><rect x="3" y="9" width="18" height="9" rx="2" /><path d="M6 14h12v7H6z" />
                          </svg>
                          SprintRay {r.machine === 'midas' ? 'Midas' : 'Pro 2'}
                          {r.machine === 'midas' && (
                            <span className="text-ink-500 font-normal normal-case tracking-normal">
                              · {t('table.mat.active')}&nbsp;: <span className="font-medium text-ink-700">{r._midasMaterialLabel}</span>
                            </span>
                          )}
                        </div>
                      </td>
                    </tr>
                  )}

                  <tr className={`border-t border-ink-100 ${r.actif ? '' : 'opacity-50'}`}>
                    <td className="px-4 py-2.5">
                      <button
                        onClick={() => toggle(r.id)}
                        title={r.actif ? t('table.toggle.off') : t('table.toggle.on')}
                        className={`w-5 h-5 rounded grid place-items-center border transition
                                    ${r.actif ? 'bg-brand-500 border-brand-500 text-white' : 'bg-white border-ink-300 text-transparent hover:border-ink-400'}`}>
                        <Icon.check />
                      </button>
                    </td>

                    <td className="px-4 py-2.5">
                      <div className="min-w-0">
                        <div className="font-medium text-ink-900 leading-tight">{label}</div>
                        {r.machine !== 'midas' && <div className="text-[11.5px] text-ink-400 leading-tight">{sub}</div>}
                        {matLabel && (
                          <div className="mt-1.5 text-[10.5px] text-ink-400">
                            {t('table.mat')}&nbsp;: <span className="text-ink-600">{matLabel}</span>
                          </div>
                        )}
                      </div>
                    </td>

                    <td className="px-3 py-2.5 text-right">
                      <NumberInput value={r.values.coutLabo}
                        onChange={(v) => setVal(r.id, 'coutLabo', v)}
                        suffix={currencySymbol}
                        ariaLabel={t('table.col.coutLabo') + ' ' + label} />
                    </td>

                    <td className="px-3 py-2.5">
                      <div className="flex items-center gap-2 justify-end">
                        <input type="range" min={0}
                          max={r.id === 'pro2-modeles' ? 80 : r.id === 'pro2-retainer' ? 40 : 30}
                          step={1}
                          value={r.values.volume}
                          onChange={(e) => setVal(r.id, 'volume', parseInt(e.target.value, 10))}
                          className="flex-1 min-w-[60px]" />
                        <NumberInput value={r.values.volume}
                          onChange={(v) => setVal(r.id, 'volume', v)}
                          ariaLabel={t('table.col.volume')} />
                      </div>
                    </td>

                    <td className="px-3 py-2.5 text-right">
                      <div className="flex flex-col items-end">
                        <NumberInput value={r.values.coutMateriau}
                          onChange={(v) => setVal(r.id, 'coutMateriau', v)}
                          suffix={currencySymbol}
                          step={0.01}
                          ariaLabel={t('table.col.materiau')} />
                        {r.def.coutMateriau == null && (
                          <span className="text-[10px] text-ink-400 italic">{t('table.mat.hint')}</span>
                        )}
                      </div>
                    </td>

                    <td className="px-3 py-2.5">
                      {r.machine === 'pro2' ? (() => {
                        const dm = r.values.designMode || 'sprintray';
                        return (
                          <div>
                            <div className="flex items-center gap-1 flex-nowrap justify-end">
                              <button onClick={() => setVal(r.id, 'designMode', 'sprintray')}
                                      className={`px-2 py-0.5 text-[11px] rounded-full border transition whitespace-nowrap
                                        ${dm === 'sprintray'
                                          ? 'bg-brand-500 border-brand-500 text-white'
                                          : 'border-ink-200 text-ink-500 hover:border-ink-400'}`}>
                                SR{r.srCost > 0 ? ` ${fmt.EUR2(r.srCost)}` : ` ${t('table.design.free')}`}
                              </button>
                              <button onClick={() => setVal(r.id, 'designMode', 'other')}
                                      className={`px-2 py-0.5 text-[11px] rounded-full border transition whitespace-nowrap
                                        ${dm !== 'sprintray'
                                          ? 'bg-brand-500 border-brand-500 text-white'
                                          : 'border-ink-200 text-ink-500 hover:border-ink-400'}`}>
                                {t('table.design.other')}
                              </button>
                            </div>
                            <div className={`mt-1 flex justify-end transition-opacity duration-150
                                             ${dm !== 'sprintray' ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}>
                              <NumberInput value={r.values.laboCost || undefined}
                                           onChange={v => setVal(r.id, 'laboCost', v)}
                                           suffix={currencySymbol}
                                           ariaLabel={t('table.design.other')}/>
                            </div>
                          </div>
                        );
                      })() : (() => {
                        const dm = r.values.designMode || 'ia';
                        const currentVal = dm === 'sprintray' ? (r.values.srCost || undefined) : (r.values.laboCost || undefined);
                        const currentKey = dm === 'sprintray' ? 'srCost' : 'laboCost';
                        return (
                          <div>
                            <div className="flex items-center gap-1 flex-nowrap justify-end">
                              <button onClick={() => setVal(r.id, 'designMode', 'ia')}
                                      className={`px-2 py-0.5 text-[11px] rounded-full border transition whitespace-nowrap
                                        ${dm === 'ia' ? 'bg-brand-500 border-brand-500 text-white' : 'border-ink-200 text-ink-500 hover:border-ink-400'}`}>
                                {t('table.design.ia')}
                              </button>
                              <button onClick={() => setVal(r.id, 'designMode', 'sprintray')}
                                      className={`px-2 py-0.5 text-[11px] rounded-full border transition whitespace-nowrap
                                        ${dm === 'sprintray' ? 'bg-brand-500 border-brand-500 text-white' : 'border-ink-200 text-ink-500 hover:border-ink-400'}`}>
                                SR
                              </button>
                              <button onClick={() => setVal(r.id, 'designMode', 'labo')}
                                      className={`px-2 py-0.5 text-[11px] rounded-full border transition whitespace-nowrap
                                        ${dm === 'labo' ? 'bg-brand-500 border-brand-500 text-white' : 'border-ink-200 text-ink-500 hover:border-ink-400'}`}>
                                {t('table.design.labo')}
                              </button>
                            </div>
                            <div className={`mt-1 flex justify-end transition-opacity duration-150
                                             ${dm !== 'ia' ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}>
                              <NumberInput value={currentVal}
                                           onChange={v => setVal(r.id, currentKey, v)}
                                           suffix={currencySymbol}
                                           ariaLabel={t('table.col.design')}/>
                            </div>
                          </div>
                        );
                      })()}
                    </td>

                    <td className="px-3 py-2.5 text-right tnum">
                      <span className={`font-medium ${c.economieMois > 0 ? 'text-emerald-700' : c.economieMois < 0 ? 'text-rose-700' : 'text-ink-400'}`}>
                        {c.economieMois === 0 ? '—' : fmt.EUR(c.economieMois)}
                      </span>
                      <div className="text-[10.5px] text-ink-400">
                        {c.economieUnit !== 0 ? `${fmt.EUR(c.economieUnit)} × ${r.values.volume}` : ''}
                      </div>
                    </td>

                    <td className="px-2 py-2.5 text-right">
                      <button onClick={() => reset(r.id)}
                        title={t('table.reset')}
                        className="text-ink-300 hover:text-brand-500 transition">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                          <path d="M3 12a9 9 0 1 0 3-6.7" /><path d="M3 4v5h5" />
                        </svg>
                      </button>
                    </td>
                  </tr>
                </React.Fragment>
              );
            })}
          </tbody>

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

Object.assign(window, { IndicationsTable });
