// arrears.jsx — Restanțieri + penalizări auto + somație digitală

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

  // Build list of apartments with arrears
  const aptsWithArrears = Object.keys(window.ARREARS_LEDGER).map(aptId => {
    const apt = state.apartments.find(a => a.id === aptId);
    const ledger = window.ARREARS_LEDGER[aptId];
    const overdue = ledger.filter(l => l.days_late > 0);
    const total = ledger.reduce((s, l) => s + (l.original - l.paid + l.penalty), 0);
    const totalOriginal = ledger.reduce((s, l) => s + (l.original - l.paid), 0);
    const totalPenalty = ledger.reduce((s, l) => s + l.penalty, 0);
    const oldestDays = Math.max(...overdue.map(l => l.days_late), 0);
    const legalAction = window.LEGAL_ACTIONS.find(la => la.apt_id === aptId);
    return { apt, ledger, overdue, total, totalOriginal, totalPenalty, oldestDays, legalAction };
  }).sort((a, b) => b.oldestDays - a.oldestDays);

  const totalDebt = aptsWithArrears.reduce((s, a) => s + a.total, 0);
  const totalPenalty = aptsWithArrears.reduce((s, a) => s + a.totalPenalty, 0);
  const chronicCount = aptsWithArrears.filter(a => a.oldestDays > 90).length;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title="Restanțieri"
        subtitle="Solduri reportate · penalizări auto · acțiuni legale conform Legii 196/2018"
        right={<Button variant="secondary" icon="download">Export raport restanțe</Button>}
      />

      {/* Legal banner */}
      <Card style={{ background: 'linear-gradient(135deg, #FFFAEB, #FEF3C7)', border: '1px solid #F59E0B' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: '#F59E0B', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, flexShrink: 0 }}>⚖️</div>
          <div style={{ flex: 1, fontSize: 13.5, color: '#78350F', lineHeight: 1.55 }}>
            <b>Conform Legii 196/2018, art. 77:</b> penalizarea de întârziere este max <b>0,2%/zi</b>, dar nu poate depăși 100% din suma datorată. După <b>30 de zile de la somația scrisă</b>, asociația poate introduce acțiune la judecătorie. BlocApp generează automat toate documentele și calculează corect penalizarea pentru fiecare lună.
          </div>
        </div>
      </Card>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 'var(--gap)' }}>
        <SummaryCard icon="receipt" iconBg="#FEE2E2" iconColor="#991B1B" label="Total restanțe" value={<>{window.fmtRONshort(totalDebt)} <span style={{ fontSize: 16, color: 'var(--muted)' }}>RON</span></>} sub={`${aptsWithArrears.length} apartamente`} />
        <SummaryCard icon="clock" iconBg="#FEF3C7" iconColor="#92400E" label="Penalizări acumulate" value={<>{window.fmtRONshort(totalPenalty)} <span style={{ fontSize: 16, color: 'var(--muted)' }}>RON</span></>} sub="Calculate auto la 0,2%/zi" />
        <SummaryCard icon="x" iconBg="#FADEDB" iconColor="#A8482F" label="Cronici (90+ zile)" value={chronicCount} sub="Eligibili pentru instanță" />
        <SummaryCard icon="check" iconBg="#DDF0E4" iconColor="#065F46" label="La zi" value={state.apartments.length - aptsWithArrears.length} sub={`din ${state.apartments.length} apt.`} />
      </div>

      {/* List of debtors */}
      <Card padded={false}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border)' }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, margin: 0, color: 'var(--ink)' }}>Apartamente cu restanțe</h3>
          <p style={{ fontSize: 12.5, color: 'var(--muted)', margin: '4px 0 0' }}>Sortat după vechime — cei mai vechi întâi</p>
        </div>
        {aptsWithArrears.map(({ apt, ledger, overdue, total, totalOriginal, totalPenalty, oldestDays, legalAction }) => (
          <DebtorRow key={apt.id} apt={apt} total={total} totalOriginal={totalOriginal} totalPenalty={totalPenalty} oldestDays={oldestDays} months={overdue.length} legalAction={legalAction} onClick={() => setSelectedApt(apt.id)} />
        ))}
      </Card>

      <Drawer open={!!selectedApt} onClose={() => setSelectedApt(null)} title={selectedApt ? `Restanțe Ap. ${state.apartments.find(a => a.id === selectedApt)?.number}` : ''} width={680}>
        {selectedApt && <DebtorDetail aptId={selectedApt} apt={state.apartments.find(a => a.id === selectedApt)} state={state} />}
      </Drawer>
    </div>
  );
}

function DebtorRow({ apt, total, totalOriginal, totalPenalty, oldestDays, months, legalAction, onClick }) {
  const severity = oldestDays > 90 ? 'critical' : oldestDays > 30 ? 'high' : 'normal';
  const colors = {
    critical: { bg: '#FEE2E2', fg: '#991B1B' },
    high:     { bg: '#FEF3C7', fg: '#92400E' },
    normal:   { bg: 'var(--surface-2)', fg: 'var(--muted)' },
  }[severity];

  return (
    <button onClick={onClick} style={{
      width: '100%', padding: '18px 24px',
      background: 'transparent', border: 0, borderBottom: '1px solid var(--border)', cursor: 'pointer',
      fontFamily: 'inherit', textAlign: 'left',
      display: 'flex', alignItems: 'center', gap: 16,
      transition: 'background 160ms ease',
    }}
    onMouseEnter={(e) => e.currentTarget.style.background = 'var(--surface-2)'}
    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
    >
      <div style={{
        width: 44, height: 44, borderRadius: 10, flexShrink: 0,
        background: colors.bg, color: colors.fg,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 14,
      }}>{apt.number}</div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 14.5, color: 'var(--ink)' }}>{apt.owner_name}</div>
        <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
          {months} lun{months === 1 ? 'ă' : 'i'} restantă · cea mai veche acum <b style={{ color: colors.fg }}>{oldestDays} zile</b>
        </div>
        {legalAction && (
          <div style={{ marginTop: 6, display: 'inline-flex', alignItems: 'center', gap: 6, padding: '2px 9px', borderRadius: 999, background: '#FEE2E2', color: '#991B1B', fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
            ⚖️ În proces — {legalActionStageLabel(legalAction.stage)}
          </div>
        )}
      </div>

      <div style={{ textAlign: 'right', flexShrink: 0 }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 19, fontWeight: 700, color: 'var(--ink)' }}>
          {window.fmtRON(total)}
        </div>
        <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2, fontFamily: 'var(--font-mono)' }}>
          principal {window.fmtRONshort(totalOriginal)} + penalizare {window.fmtRONshort(totalPenalty)}
        </div>
      </div>

      <Icon name="chevRight" size={16} style={{ color: 'var(--muted)', flexShrink: 0 }} />
    </button>
  );
}

function legalActionStageLabel(stage) {
  return {
    notification_sent: 'Atenționare trimisă',
    formal_demand: 'Somatie',
    court_filed: 'Dosar instanță',
    enforcer: 'Executor judecătoresc',
    resolved: 'Rezolvat',
  }[stage] || stage;
}

function DebtorDetail({ aptId, apt, state }) {
  const ledger = window.ARREARS_LEDGER[aptId] || [];
  const legalAction = window.LEGAL_ACTIONS.find(la => la.apt_id === aptId);
  const [showActionConfirm, setShowActionConfirm] = React.useState(null);
  const toast = useToast();
  const oldestDays = Math.max(...ledger.map(l => l.days_late), 0);
  const total = ledger.reduce((s, l) => s + (l.original - l.paid + l.penalty), 0);
  const canEscalate = oldestDays > 90;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* Owner header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{
          width: 56, height: 56, borderRadius: 999,
          background: 'var(--accent)', color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20,
        }}>{apt.owner_name.split(' ').map(p => p[0]).join('').slice(0, 2)}</div>
        <div style={{ flex: 1 }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', margin: 0 }}>{apt.owner_name}</h3>
          <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 2 }}>Ap. {apt.number} · {apt.owner_phone}</div>
        </div>
        <Button size="sm" variant="ghost" icon="phone">Sună</Button>
      </div>

      {/* Total card */}
      <div style={{ padding: 18, borderRadius: 14, background: 'linear-gradient(135deg, #FEE2E2, #FECACA)', border: '1px solid #DC2626' }}>
        <div style={{ fontSize: 11, color: '#7F1D1D', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Total restant</div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 700, color: '#991B1B', letterSpacing: '-0.02em', lineHeight: 1 }}>
          {window.fmtRON(total)}
        </div>
        <div style={{ fontSize: 12, color: '#7F1D1D', marginTop: 10, lineHeight: 1.5 }}>
          Cea mai veche datorie: <b>{oldestDays} zile</b>
          {canEscalate && <span> · Eligibilă pentru acțiune în instanță</span>}
        </div>
      </div>

      {/* Per-month breakdown */}
      <div>
        <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 10 }}>Defalcare pe luni</div>
        <Card padded={false}>
          {ledger.map((l, i) => (
            <div key={i} style={{
              padding: '12px 16px',
              borderBottom: i < ledger.length - 1 ? '1px solid var(--border)' : 'none',
              display: 'flex', alignItems: 'center', gap: 12, fontSize: 13,
            }}>
              <div style={{
                width: 8, height: 8, borderRadius: 999,
                background: l.days_late > 90 ? '#DC2626' : l.days_late > 30 ? '#D97706' : l.days_late > 0 ? '#F59E0B' : '#10B981',
              }} />
              <div style={{ flex: 1, fontWeight: 500, color: 'var(--ink)' }}>{l.month}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--muted)', minWidth: 70, textAlign: 'right' }}>
                {l.days_late > 0 ? `+${l.days_late}z` : 'în termen'}
              </div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12.5, color: 'var(--ink-2)', minWidth: 90, textAlign: 'right' }}>
                {window.fmtRON(l.original - l.paid)}
              </div>
              {l.penalty > 0 && (
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: '#DC2626', minWidth: 80, textAlign: 'right', fontWeight: 600 }}>
                  +{l.penalty.toFixed(2)} pen.
                </div>
              )}
            </div>
          ))}
        </Card>
      </div>

      {/* Penalty calculation */}
      <Card style={{ background: 'var(--surface-2)', boxShadow: 'none' }}>
        <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 8 }}>Cum se calculează penalizarea</div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.6 }}>
          penalizare = sumă × 0.002 × zile_întârziere<br/>
          (max 100% din sumă · Legea 196/2018 art. 77)
        </div>
      </Card>

      {/* Legal action timeline */}
      {legalAction ? (
        <div>
          <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 10 }}>Cronologie acțiune legală</div>
          <div style={{ position: 'relative', paddingLeft: 24 }}>
            <div style={{ position: 'absolute', left: 11, top: 6, bottom: 6, width: 2, background: 'var(--border)' }} />
            {legalAction.actions.map((a, i) => (
              <div key={i} style={{ position: 'relative', marginBottom: 12 }}>
                <div style={{
                  position: 'absolute', left: -18, top: 0,
                  width: 24, height: 24, borderRadius: 999,
                  background: i === legalAction.actions.length - 1 ? '#DC2626' : 'var(--surface)', color: i === legalAction.actions.length - 1 ? '#fff' : 'var(--muted)',
                  border: '2px solid ' + (i === legalAction.actions.length - 1 ? '#DC2626' : 'var(--border)'),
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontWeight: 700,
                }}>{i === legalAction.actions.length - 1 ? '!' : '✓'}</div>
                <div style={{ fontSize: 11, color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>{a.ts}</div>
                <div style={{ fontSize: 13, color: 'var(--ink)', lineHeight: 1.45, marginTop: 2 }}>{a.text}</div>
              </div>
            ))}
          </div>
        </div>
      ) : null}

      {/* Action buttons */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <Button variant="primary" full icon="mail" onClick={() => toast('Atenționare trimisă prin email + WhatsApp')}>
          Trimite atenționare amiabilă
        </Button>
        <Button variant="secondary" full icon="print" onClick={() => toast('Somatie generată — confirmare prin Poșta Română recomandată')}>
          Generează somație oficială (PDF + curier)
        </Button>
        {canEscalate && (
          <Button variant="danger" full icon="sparkles" onClick={() => toast('Dosar pregătit · cost estimat 380 RON taxă judiciară · va fi trimis avocatului')}>
            ⚖️ Introdu acțiune în instanță
          </Button>
        )}
        <Button variant="ghost" full icon="check" onClick={() => toast('Plan eșalonat creat')}>
          Propune plan eșalonat de plată
        </Button>
      </div>
    </div>
  );
}

Object.assign(window, { ArrearsScreen });
