/* TotalesTab.jsx — auto-mirrors every Registros project and shows per-row
   totals aggregated by month or by year (3 comparison modes). */
const { useState: useST } = React;

function MiniSeg({ t, value, options, onChange }) {
  return (
    <div style={{ display: 'flex', gap: 3, background: t.surfCont, borderRadius: 100, padding: 3 }}>
      {options.map((o) => {
        const sel = o.v === value;
        return <button key={o.v} onClick={() => onChange(o.v)} style={{ border: 'none', cursor: 'pointer', padding: '8px 16px', borderRadius: 100, background: sel ? t.primary : 'transparent', color: sel ? t.onPrimary : t.onSurfaceVariant, fontSize: 13, fontWeight: 600 }}>{o.l}</button>;
      })}
    </div>
  );
}

function TotalsDetail({ t, L, lang, project, onBack, showMed }) {
  const [mode, setMode] = useST('month');
  const [yearOpt, setYearOpt] = useST(0);
  const [snack, setSnack] = useST(null);
  const scrollRef = React.useRef(null);
  const todayIso = window.APP.dayOffset(0);
  const curYear = +todayIso.slice(0, 4);
  const cols = window.APP.totalesColumns(mode, yearOpt, todayIso, lang);

  React.useEffect(() => { if (!snack) return; const id = setTimeout(() => setSnack(null), 2600); return () => clearTimeout(id); }, [snack]);

  const sendSummary = () => {
    if (!project.email) { setSnack(L.noEmailSet); return; }
    let py = +todayIso.slice(0, 4), pm = +todayIso.slice(5, 7) - 1;
    if (pm === 0) { pm = 12; py -= 1; }
    const prevYm = `${py}-${String(pm).padStart(2, '0')}`;
    const lines = project.rows.map((r) => ({ name: r.name, val: window.APP.sumRow(project, r.id, (d) => d.slice(0, 7) === prevYm), med: window.APP.medRowVal(project, r.id, prevYm) }));
    const w = Math.max(8, ...lines.map((l) => l.name.length)) + 4;
    let rowsTxt;
    if (showMed) {
      const VW = 8;            // value column width
      const GAP = '          '; // ~1 cm gap separating the Med column
      const header = ''.padEnd(w) + ''.padEnd(VW) + GAP + 'Med';
      rowsTxt = [header].concat(lines.map((l) => l.name.padEnd(w) + String(l.val).padEnd(VW) + GAP + l.med));
    } else {
      rowsTxt = lines.map((l) => l.name.padEnd(w) + l.val);
    }
    const body = L.emailBody + '\n\n' + rowsTxt.join('\n');
    const subject = `${project.title} — ${window.APP.monthLong(prevYm, lang)}`;
    const href = `mailto:${encodeURIComponent(project.email)}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    window.location.href = href;
  };

  const LBL = 152, CW = 70, CH = 52, TW = 60;
  const showSigma = mode !== 'year';
  const colIsCurrent = (c) => (c.type === 'month' ? +c.ym.slice(0, 4) === curYear : c.y === curYear);
  const val = (rid, c) => window.APP.colValue(project, rid, c);
  const colTotal = (c) => project.rows.reduce((s, r) => s + val(r.id, c), 0);
  const rowTotal = (rid) => cols.reduce((s, c) => s + val(rid, c), 0);
  const grand = cols.reduce((s, c) => s + colTotal(c), 0);

  return (
    <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', background: t.surface, position: 'relative' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '6px 6px 6px 4px', background: t.primaryContainer, color: t.onPrimaryContainer, flexShrink: 0 }}>
        <IconButton name="back" color={t.onPrimaryContainer} onClick={onBack} label={L.cancel} />
        <span style={{ flex: 1, fontSize: 21, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{project.title}</span>
        {mode === 'month' && <IconButton name="mail" color={t.onPrimaryContainer} onClick={sendSummary} label={L.sendEmail} />}
      </div>

      <div style={{ padding: '14px 16px 6px', flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, color: t.onSurfaceVariant }}>{L.groupBy}</span>
          <MiniSeg t={t} value={mode} onChange={setMode} options={[{ v: 'month', l: L.monthLabel }, { v: 'year', l: L.yearLabel }]} />
        </div>
        {mode === 'year' && (
          <select value={yearOpt} onChange={(e) => setYearOpt(+e.target.value)} style={{
            width: '100%', boxSizing: 'border-box', padding: '12px 14px', fontSize: 13.5, fontWeight: 600,
            borderRadius: 12, border: `1px solid ${t.outline}`, background: t.surfContLow, color: t.onSurface, fontFamily: 'inherit', cursor: 'pointer',
          }}>
            {L.yearOpts.map((o, i) => <option key={i} value={i}>{o}</option>)}
          </select>
        )}
      </div>

      <div ref={scrollRef} style={{ flex: 1, minHeight: 0, overflow: 'auto', marginTop: 4 }}>
        <div style={{ display: 'inline-grid', gridTemplateColumns: `${LBL}px repeat(${cols.length}, ${CW}px)${showSigma ? ` ${TW}px` : ''}` }}>
          <div style={{ position: 'sticky', top: 0, left: 0, zIndex: 5, background: t.surfCont, height: 54, display: 'flex', alignItems: 'flex-end', padding: '0 8px 8px 14px', boxSizing: 'border-box' }}>
            <span style={{ fontSize: 11, fontWeight: 700, color: t.onSurfaceVariant }}>{lang === 'es' ? 'Categoría' : 'Category'}</span>
          </div>
          {cols.map((c, ci) => {
            const cur = colIsCurrent(c);
            return (
              <div key={ci} style={{ position: 'sticky', top: 0, zIndex: 4, background: cur ? t.primaryContainer : t.surfCont, height: 54, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 1, borderLeft: ci > 0 && c.type === 'month' && ci % 2 === 0 && cols.length === 6 ? `1px solid ${t.outlineVariant}66` : 'none' }}>
                <span style={{ fontSize: 14, fontWeight: 700, color: cur ? t.onPrimaryContainer : t.onSurface, textTransform: 'capitalize', lineHeight: 1.1, textAlign: 'center' }}>{c.label}</span>
                {c.sub && <span style={{ fontSize: 9.5, color: cur ? t.onPrimaryContainer : t.onSurfaceVariant, opacity: 0.8 }}>{c.sub}</span>}
              </div>
            );
          })}
          {showSigma && <div style={{ position: 'sticky', top: 0, zIndex: 4, background: t.surfCont, height: 54, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><span style={{ fontSize: 11, fontWeight: 700, color: t.onSurfaceVariant }}>Σ</span></div>}

          {project.rows.map((r) => (
            <React.Fragment key={r.id}>
              <div style={{ position: 'sticky', left: 0, zIndex: 3, background: t.surface, borderRight: `1px solid ${t.outlineVariant}55`, height: CH, display: 'flex', alignItems: 'center', padding: '0 8px 0 14px', boxSizing: 'border-box' }}>
                <span style={{ fontSize: 15, fontWeight: 600, color: t.onSurface, overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', lineHeight: 1.15 }}>{r.name}</span>
              </div>
              {cols.map((c, ci) => {
                const v = val(r.id, c);
                return <div key={ci} style={{ height: CH, width: CW, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 17, fontWeight: v ? 700 : 400, color: v ? t.onSurface : t.onSurfaceVariant + '55', background: colIsCurrent(c) ? t.primaryContainer + '40' : 'transparent' }}>{v}</div>;
              })}
              {showSigma && <div style={{ height: CH, width: TW, display: 'flex', alignItems: 'center', justifyContent: 'center', background: t.surfContLow, fontSize: 16, fontWeight: 700, color: t.primary }}>{rowTotal(r.id)}</div>}
            </React.Fragment>
          ))}

          <div style={{ position: 'sticky', left: 0, bottom: 0, zIndex: 5, background: t.surfContHigh, height: 48, display: 'flex', alignItems: 'center', padding: '0 14px', borderRight: `1px solid ${t.outlineVariant}55` }}><span style={{ fontSize: 14, fontWeight: 700, color: t.onSurface }}>{L.total}</span></div>
          {cols.map((c, ci) => <div key={ci} style={{ position: 'sticky', bottom: 0, zIndex: 4, background: t.surfContHigh, height: 48, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontWeight: 700, color: t.onSurface }}>{colTotal(c)}</div>)}
          {showSigma && <div style={{ position: 'sticky', bottom: 0, zIndex: 4, background: t.primaryContainer, height: 48, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, fontWeight: 800, color: t.onPrimaryContainer }}>{grand}</div>}
        </div>
      </div>

      <HSlider t={t} scrollRef={scrollRef} deps={[mode, yearOpt, cols.length]} />
      {snack && <div style={{ position: 'absolute', left: 16, right: 16, bottom: 70, zIndex: 90, background: t.onSurface, color: t.surface, padding: '13px 18px', borderRadius: 12, fontSize: 13.5, fontWeight: 500, boxShadow: '0 6px 18px rgba(0,0,0,.28)' }}>{snack}</div>}
    </div>
  );
}

function TotalesTab({ t, L, lang, style, projects, showMed }) {
  const [openId, setOpenId] = useST(null);
  const open = projects.find((p) => p.id === openId);
  if (open) return <TotalsDetail t={t} L={L} lang={lang} project={open} onBack={() => setOpenId(null)} showMed={showMed} />;

  if (projects.length === 0) {
    return (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: 30, gap: 6 }}>
        <div style={{ width: 84, height: 84, borderRadius: 26, background: t.surfContHigh, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 12 }}><Icon name="bars" size={38} color={t.onSurfaceVariant} /></div>
        <div style={{ fontSize: 15, color: t.onSurfaceVariant, maxWidth: 250, lineHeight: 1.45 }}>{L.totalsEmpty}</div>
      </div>
    );
  }
  const curYear = +window.APP.dayOffset(0).slice(0, 4);
  return (
    <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '10px 16px 30px' }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {projects.map((p) => {
          const yTot = p.rows.reduce((s, r) => s + window.APP.sumRow(p, r.id, (d) => +d.slice(0, 4) === curYear), 0);
          return (
            <button key={p.id} onClick={() => setOpenId(p.id)} style={{ textAlign: 'left', width: '100%', border: style.cardBorder ? `1px solid ${t.outlineVariant}` : 'none', background: t[style.cardBg], color: t.onSurface, borderRadius: style.cardRadius, padding: '18px 20px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 16, boxSizing: 'border-box' }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 20, fontWeight: 600, lineHeight: 1.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.title}</div>
                <div style={{ fontSize: 15, color: t.onSurfaceVariant, marginTop: 5 }}>{p.rows.length} {lang === 'es' ? 'filas' : 'rows'} · {curYear}</div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minWidth: 64, height: 64, borderRadius: 18, background: t.primaryContainer, color: t.onPrimaryContainer, padding: '0 10px' }}>
                <span style={{ fontSize: 28, fontWeight: 700, lineHeight: 1 }}>{yTot}</span>
                <span style={{ fontSize: 12, opacity: 0.85, marginTop: 3 }}>{curYear}</span>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { TotalesTab });
