// rules.jsx — Admin screen: "Reguli scară" — participation matrix

function RulesScreen({ state, tr, lang }) {
  const [selectedApt, setSelectedApt] = React.useState(null);
  const toast = useToast();

  // Toggle a per-apt flag, recompute charges
  const toggleFlag = (aptId, flag) => {
    state.setApartments(apts => apts.map(a => a.id === aptId ? { ...a, [flag]: !a[flag] } : a));
    // re-calc after state update
    setTimeout(() => state.setCharges(state.calcCharges()), 0);
    toast(lang === 'ro' ? 'Regulă actualizată — sumele au fost recalculate' : 'Rule updated — amounts recalculated');
  };

  // Cycle apt type
  const cycleAptType = (aptId) => {
    const types = ['rezidential', 'comercial', 'garaj'];
    state.setApartments(apts => apts.map(a => {
      if (a.id !== aptId) return a;
      const next = types[(types.indexOf(a.apt_type) + 1) % types.length];
      return { ...a, apt_type: next };
    }));
    setTimeout(() => state.setCharges(state.calcCharges()), 0);
  };

  // Stats per category: how many participate
  const stats = React.useMemo(() => {
    const out = {};
    window.CATEGORIES.forEach(c => {
      const total = state.apartments.length;
      const part = state.apartments.filter(a => window.aptParticipates(a, c).participates).length;
      out[c.id] = { part, total, pct: (part / total) * 100 };
    });
    return out;
  }, [state.apartments]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1400 }}>
      <PageHeader
        title={lang === 'ro' ? 'Reguli scară' : 'Building rules'}
        subtitle={lang === 'ro' ? 'Cine plătește ce — matricea participării. Apasă pe celule pentru a edita.' : 'Who pays what — participation matrix. Click cells to edit.'}
        right={<Button variant="secondary" icon="info">{lang === 'ro' ? 'Ghid hotărâri AGA' : 'AGA decisions guide'}</Button>}
      />

      {/* Quick explanation */}
      <Card style={{ background: 'var(--primary-light)', border: '1px solid color-mix(in oklab, var(--primary), transparent 80%)' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10, flexShrink: 0,
            background: 'var(--primary)', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><Icon name="info" size={20} stroke={2} /></div>
          <div style={{ flex: 1, fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.55 }}>
            <b style={{ color: 'var(--ink)' }}>{lang === 'ro' ? 'Realitatea unui bloc românesc:' : 'Romanian apartment building reality:'}</b><br/>
            {lang === 'ro'
              ? 'Parterul nu plătește lift (hotărâre AGA). Apartamentele cu centrală proprie nu plătesc CET. Cei cu boiler propriu nu plătesc apă caldă. Spațiul comercial are alte reguli. Schimbarea oricărei reguli recalculează automat lista.'
              : 'Ground floor doesn\'t pay for lift. Apartments with own gas boiler don\'t pay CET. Etc. Changing any rule auto-recalculates the list.'}
          </div>
        </div>
      </Card>

      {/* Matrix */}
      <Card padded={false} style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'separate', borderSpacing: 0, fontSize: 13 }}>
          <thead>
            <tr>
              <th style={ruleHeaderStyle({ left: true, sticky: true, width: 220 })}>
                {lang === 'ro' ? 'Apartament' : 'Apartment'}
              </th>
              <th style={ruleHeaderStyle({ width: 100 })}>
                {lang === 'ro' ? 'Tip' : 'Type'}
              </th>
              {window.CATEGORIES.map(cat => (
                <th key={cat.id} style={{ ...ruleHeaderStyle({ width: 92 }), color: cat.color }}>
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2, padding: '6px 4px' }}>
                    <span style={{ fontSize: 18 }}>{cat.icon}</span>
                    <span style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--ink-2)', lineHeight: 1.1, textAlign: 'center', textTransform: 'none', letterSpacing: 0 }}>
                      {cat.name}
                    </span>
                  </div>
                </th>
              ))}
              <th style={ruleHeaderStyle({ width: 80 })}>
                {lang === 'ro' ? 'Total/lună' : 'Total/mo'}
              </th>
            </tr>
            <tr style={{ background: 'var(--surface-2)' }}>
              <th style={{ ...ruleHeaderStyle({ left: true, sticky: true, width: 220 }), background: 'var(--surface-2)', fontWeight: 500, fontSize: 11, color: 'var(--muted)', padding: '6px 16px' }}>
                {lang === 'ro' ? 'Participare' : 'Participation'}
              </th>
              <th></th>
              {window.CATEGORIES.map(cat => (
                <th key={cat.id} style={{ padding: '6px 4px', textAlign: 'center', fontWeight: 500, fontSize: 11, color: 'var(--muted)', background: 'var(--surface-2)' }}>
                  {stats[cat.id].part}/{stats[cat.id].total}
                </th>
              ))}
              <th style={{ background: 'var(--surface-2)' }}></th>
            </tr>
          </thead>
          <tbody>
            {state.apartments.map(a => {
              const ch = state.charges[a.id];
              return (
                <tr key={a.id} style={{ borderTop: '1px solid var(--border)' }}>
                  <td style={{ padding: '14px 16px', position: 'sticky', left: 0, background: 'var(--surface)', zIndex: 2 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <div style={{
                        width: 32, height: 32, borderRadius: 8,
                        background: 'var(--primary-light)', color: 'var(--primary)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 12,
                      }}>{a.number}</div>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 13, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 150 }}>{a.owner_name}</div>
                        <div style={{ fontSize: 11, color: 'var(--muted)', display: 'flex', gap: 6 }}>
                          <span>{window.floorLabel(a.floor)}</span>
                          {a.has_own_centrala && <span title="Centrală proprie" style={{ color: '#F97316' }}>🔥</span>}
                          {a.has_own_water_heater && <span title="Boiler propriu" style={{ color: '#3B82F6' }}>♨️</span>}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: '14px 8px', textAlign: 'center' }}>
                    <button onClick={() => cycleAptType(a.id)} title={lang === 'ro' ? 'Schimbă tip' : 'Cycle type'} style={{
                      padding: '4px 10px', borderRadius: 999,
                      background: aptTypeColor(a.apt_type).bg, color: aptTypeColor(a.apt_type).fg,
                      border: 0, cursor: 'pointer',
                      fontFamily: 'inherit', fontSize: 11, fontWeight: 600,
                    }}>{aptTypeLabel(a.apt_type, lang)}</button>
                  </td>
                  {window.CATEGORIES.map(cat => {
                    const part = window.aptParticipates(a, cat);
                    const entry = ch?.breakdown[cat.id];
                    const editable = cat.id === 'c5' || cat.id === 'c3' || cat.id === 'c2'; // lift, CET, apă caldă
                    return (
                      <td key={cat.id} style={{ padding: '8px 4px', textAlign: 'center', borderLeft: '1px solid var(--border)' }}>
                        <MatrixCell
                          participates={part.participates}
                          reason={part.reason}
                          amount={entry?.amount}
                          editable={editable}
                          onClick={() => {
                            if (cat.id === 'c5') toggleFlag(a.id, 'pays_lift');
                            else if (cat.id === 'c3') toggleFlag(a.id, 'has_own_centrala');
                            else if (cat.id === 'c2') toggleFlag(a.id, 'has_own_water_heater');
                          }}
                        />
                      </td>
                    );
                  })}
                  <td style={{ padding: '14px 12px', textAlign: 'right', fontFamily: 'var(--font-mono)', fontWeight: 700, color: 'var(--ink)', fontSize: 13 }}>
                    {ch ? window.fmtRONshort(ch.total) : '—'}
                  </td>
                </tr>
              );
            })}
            {/* Totals row */}
            <tr style={{ background: 'var(--surface-2)', borderTop: '2px solid var(--border)' }}>
              <td style={{ padding: '12px 16px', position: 'sticky', left: 0, background: 'var(--surface-2)', fontWeight: 700, fontSize: 12.5, color: 'var(--ink)' }}>
                {lang === 'ro' ? 'Total / categorie' : 'Total / category'}
              </td>
              <td></td>
              {window.CATEGORIES.map(cat => {
                const exp = state.expenses.filter(e => e.category_id === cat.id).reduce((s, e) => s + parseFloat(e.amount), 0);
                return (
                  <td key={cat.id} style={{ padding: '12px 4px', textAlign: 'center', fontFamily: 'var(--font-mono)', fontSize: 11.5, fontWeight: 600, color: 'var(--ink)' }}>
                    {exp > 0 ? window.fmtRONshort(exp) : '—'}
                  </td>
                );
              })}
              <td style={{ padding: '12px 12px', textAlign: 'right', fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 14, color: 'var(--primary)' }}>
                {window.fmtRONshort(state.totals.totalExpense)}
              </td>
            </tr>
          </tbody>
        </table>
      </Card>

      {/* Legend */}
      <Card>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, fontSize: 12.5, color: 'var(--ink-2)', flexWrap: 'wrap' }}>
          <span style={{ fontWeight: 600, color: 'var(--ink)' }}>{lang === 'ro' ? 'Legendă:' : 'Legend:'}</span>
          <LegendItem color="var(--success)" label={lang === 'ro' ? 'Plătește (sumă afișată)' : 'Pays (shown amount)'} />
          <LegendItem color="var(--muted)" label={lang === 'ro' ? 'Scutit (cu motiv)' : 'Excluded (with reason)'} />
          <span style={{ color: 'var(--muted)', fontSize: 11.5 }}>
            🔥 {lang === 'ro' ? 'centrală proprie' : 'own boiler'} · ♨️ {lang === 'ro' ? 'boiler propriu' : 'own water heater'} · {lang === 'ro' ? 'Apasă pe Lift / CET / Apă caldă pentru a comuta' : 'Click Lift / CET / Hot water to toggle'}
        </span>
        </div>
      </Card>
    </div>
  );
}

function MatrixCell({ participates, reason, amount, editable, onClick }) {
  if (participates) {
    return (
      <button onClick={editable ? onClick : undefined} disabled={!editable} style={{
        width: '100%', padding: '8px 4px', borderRadius: 8,
        background: 'var(--success-bg)', color: 'var(--success-fg)',
        border: 0, cursor: editable ? 'pointer' : 'default',
        fontFamily: 'inherit',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
        transition: 'transform 120ms ease, background 160ms ease',
      }}
      onMouseEnter={(e) => editable && (e.currentTarget.style.transform = 'scale(1.04)')}
      onMouseLeave={(e) => editable && (e.currentTarget.style.transform = 'scale(1)')}
      >
        <Icon name="check" size={13} stroke={2.4} />
        {amount > 0 && (
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, fontWeight: 600 }}>
            {amount.toFixed(0)}
          </span>
        )}
      </button>
    );
  }
  return (
    <button onClick={editable ? onClick : undefined} disabled={!editable} title={reason} style={{
      width: '100%', padding: '8px 4px', borderRadius: 8,
      background: 'var(--neutral-bg)', color: 'var(--muted)',
      border: '1px dashed var(--border)', cursor: editable ? 'pointer' : 'default',
      fontFamily: 'inherit',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
    }}>
      <Icon name="x" size={12} />
      <span style={{ fontSize: 9, color: 'var(--muted)' }}>—</span>
    </button>
  );
}

function ruleHeaderStyle({ left, sticky, width }) {
  return {
    padding: '12px 8px',
    textAlign: left ? 'left' : 'center',
    fontWeight: 600, fontSize: 11, color: 'var(--muted)',
    textTransform: 'uppercase', letterSpacing: '0.04em',
    background: 'var(--surface)',
    borderBottom: '1px solid var(--border)',
    position: sticky ? 'sticky' : 'static',
    left: sticky ? 0 : 'auto',
    zIndex: sticky ? 3 : 1,
    width: width ? width : 'auto',
    minWidth: width ? width : 'auto',
  };
}

function aptTypeLabel(t, lang) {
  if (t === 'rezidential') return lang === 'ro' ? 'Locuință' : 'Residential';
  if (t === 'comercial')   return lang === 'ro' ? 'Comercial' : 'Commercial';
  if (t === 'garaj')       return lang === 'ro' ? 'Garaj' : 'Garage';
  return t;
}

function aptTypeColor(t) {
  if (t === 'rezidential') return { bg: 'var(--success-bg)', fg: 'var(--success-fg)' };
  if (t === 'comercial')   return { bg: 'var(--warning-bg)', fg: 'var(--warning-fg)' };
  if (t === 'garaj')       return { bg: 'var(--neutral-bg)', fg: 'var(--neutral-fg)' };
  return { bg: 'var(--neutral-bg)', fg: 'var(--neutral-fg)' };
}

function LegendItem({ color, label }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
      <span style={{ width: 10, height: 10, borderRadius: 3, background: color }} />
      {label}
    </span>
  );
}

window.RulesScreen = RulesScreen;
