// audit.jsx — Cenzor audit automat + Cadastru ANCPI + Fiscal D112/D101

// ─────────────────────────────────────────────────────────────
// Mock data
// ─────────────────────────────────────────────────────────────
window.AUDIT_REPORTS = [
  {
    id: 'au_1', year: 2024, status: 'final', date: '2025-02-15',
    auditor: 'BlocApp Auditor AI · supervised',
    findings: [
      { type: 'ok', text: '156 facturi reconciliate cu extrasul BT (100%)' },
      { type: 'ok', text: 'Toate cheltuielile au justificare în factură ANAF' },
      { type: 'ok', text: 'Fond reparații închis cu sold pozitiv 24.180 RON' },
      { type: 'minor', text: '3 facturi cu sume rotunjite la nivel de bun (acceptabil)' },
      { type: 'minor', text: 'Lipsește semnătura cenzor anterior pe 2 PV-uri din 2023' },
    ],
    signed: true, doc: 'raport-cenzor-2024.pdf',
  },
];

window.CADASTRE_RECORDS = [
  { apt_id: 'a1', cf_nr: 'CF 400123-C1-U1', real_owner: 'Ionescu Maria', registered_owner: 'Ionescu Maria', match: true, last_check: '2025-09-12' },
  { apt_id: 'a4', cf_nr: 'CF 400123-C1-U4', real_owner: 'Constantinescu Ion și Constantinescu Elena', registered_owner: 'Constantinescu Ion', match: 'partial', last_check: '2025-09-12', note: 'Soție lipsă în registrul scării' },
  { apt_id: 'a8', cf_nr: 'CF 400123-C1-U8', real_owner: 'Heredia Estate (în succesiune)', registered_owner: 'Tudorescu Mihai', match: false, last_check: '2025-11-10', note: 'Proprietar decedat — succesiune în curs' },
];

window.FISCAL_DECLARATIONS = [
  { id: 'd_1', type: 'D112', period: 'Octombrie 2025', deadline: '2025-11-25', status: 'submitted', submitted_at: '2025-11-15', amount: 142.50, note: 'CAS/CASS pentru femeia de serviciu' },
  { id: 'd_2', type: 'D112', period: 'Noiembrie 2025', deadline: '2025-12-25', status: 'draft', amount: 142.50 },
  { id: 'd_3', type: 'D205', period: 'Anual 2024', deadline: '2025-02-28', status: 'submitted', submitted_at: '2025-02-20', note: 'Venituri PFA administrator' },
  { id: 'd_4', type: 'Bilanț', period: 'Anual 2024', deadline: '2025-05-31', status: 'submitted', submitted_at: '2025-05-22' },
];

// ═════════════════════════════════════════════════════════════
// Cenzor audit automat
// ═════════════════════════════════════════════════════════════
function AuditScreen({ state, tr, lang }) {
  const toast = useToast();
  const latest = window.AUDIT_REPORTS[0];

  const okCount = latest.findings.filter(f => f.type === 'ok').length;
  const minorCount = latest.findings.filter(f => f.type === 'minor').length;
  const criticalCount = latest.findings.filter(f => f.type === 'critical').length;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title="Audit cenzor automat"
        subtitle="Raport cenzor generat automat din toate tranzacțiile · alternativă legală la cenzor uman"
        right={<Button variant="primary" icon="sparkles" onClick={() => toast('Raport audit generat din datele 2025')}>Generează raport 2025</Button>}
      />

      {/* Why */}
      <Card style={{ background: 'linear-gradient(135deg, #DDF0E4, #BBF7D0)', border: '1px solid #059669' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: '#059669', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, flexShrink: 0 }}>🔍</div>
          <div style={{ fontSize: 13.5, color: '#065F46', lineHeight: 1.55 }}>
            <b>Problema reală:</b> 70% din scări nu au cenzor (nimeni nu vrea, nimeni nu plătește). Legea cere obligatoriu. BlocApp generează raportul cenzorului <b>din datele deja prezente</b>: reconciliază facturi ANAF cu extrasul BT, verifică semnături Vault, validează cvorum AGA. Output: PDF semnat digital, opozabil. Lege 196/2018 art. 56 alin (4) permite cenzor extern (nu trebuie să fie locatar).
          </div>
        </div>
      </Card>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 'var(--gap)' }}>
        <SummaryCard icon="check" iconBg="#DDF0E4" iconColor="#065F46" label="Verificări OK" value={okCount} sub="100% reconciliat" />
        <SummaryCard icon="info" iconBg="#FEF3C7" iconColor="#92400E" label="Observații minore" value={minorCount} sub="Acceptabile" />
        <SummaryCard icon="x" iconBg="#FEE2E2" iconColor="#991B1B" label="Probleme critice" value={criticalCount} sub="Niciuna" />
        <SummaryCard icon="receipt" iconBg="#E0F2FE" iconColor="#0369A1" label="Facturi auditate" value="156" sub="2024" />
      </div>

      {/* Latest report */}
      <Card>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 18 }}>
          <div style={{ width: 56, height: 70, borderRadius: 8, background: 'linear-gradient(160deg, #fff, #f5f0e6)', border: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28, flexShrink: 0 }}>📄</div>
          <div style={{ flex: 1 }}>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', margin: 0 }}>Raport cenzor exercițiul financiar {latest.year}</h3>
            <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 4 }}>
              {latest.auditor} · finalizat {new Date(latest.date).toLocaleDateString('ro-RO', { day: 'numeric', month: 'long', year: 'numeric' })}
            </div>
            <div style={{ marginTop: 6, display: 'flex', gap: 6 }}>
              {latest.signed && <span style={{ padding: '3px 9px', borderRadius: 999, background: '#DDF0E4', color: '#065F46', fontSize: 11, fontWeight: 700 }}>✓ Semnat digital</span>}
              <span style={{ padding: '3px 9px', borderRadius: 999, background: '#E0F2FE', color: '#0369A1', fontSize: 11, fontWeight: 700 }}>Aprobat AGA</span>
            </div>
          </div>
          <Button variant="secondary" icon="download">PDF raport</Button>
        </div>

        <div style={{ fontSize: 12, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 10 }}>Concluzii audit</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {latest.findings.map((f, i) => (
            <div key={i} style={{
              padding: '10px 14px', borderRadius: 10,
              background: f.type === 'ok' ? '#F0FDF4' : f.type === 'minor' ? '#FFFAEB' : '#FEF2F2',
              borderLeft: '3px solid ' + (f.type === 'ok' ? '#059669' : f.type === 'minor' ? '#D97706' : '#DC2626'),
              fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5,
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <span style={{ fontSize: 16 }}>{f.type === 'ok' ? '✓' : f.type === 'minor' ? '⚠' : '✗'}</span>
              {f.text}
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// Cadastre — verifică proprietarul real ANCPI
// ═════════════════════════════════════════════════════════════
function CadastreScreen({ state, tr, lang }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title="Cadastru ANCPI"
        subtitle="Verificare automată a proprietarilor în Registrul de Carte Funciară · semestrial"
        right={<Button variant="primary" icon="sparkles">Reverifică toate</Button>}
      />
      <Card style={{ background: 'linear-gradient(135deg, #E0F2FE, #cae8f8)', border: '1px solid #0EA5E9' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: '#0EA5E9', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, flexShrink: 0 }}>📍</div>
          <div style={{ fontSize: 13.5, color: '#0C4A6E', lineHeight: 1.55 }}>
            <b>Cum funcționează:</b> BlocApp se conectează la API ANCPI și verifică automat (semestrial) că proprietarul listat în scară e cel real conform Cărții Funciare. Detectează: soți lipsă, succesiuni nedeclarate, vânzări neraportate, schimbări de proprietar. Critic pentru votul AGA — votul venit de la cineva care nu mai e proprietar e nul.
          </div>
        </div>
      </Card>
      <Card padded={false}>
        {window.CADASTRE_RECORDS.map(r => {
          const apt = state.apartments.find(a => a.id === r.apt_id);
          const statusBadge = r.match === true ? { bg: '#DDF0E4', fg: '#065F46', label: '✓ Conform' }
                            : r.match === 'partial' ? { bg: '#FEF3C7', fg: '#92400E', label: '⚠ Parțial' }
                            : { bg: '#FEE2E2', fg: '#991B1B', label: '✗ Discrepanță' };
          return (
            <div key={r.apt_id} style={{ padding: '16px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 44, height: 44, borderRadius: 11, background: 'var(--surface-2)', color: 'var(--muted)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 13 }}>{apt?.number}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>Ap. {apt?.number} · CF {r.cf_nr}</div>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
                  În scară: <b>{r.registered_owner}</b><br/>
                  La ANCPI: <b style={{ color: r.match === true ? 'var(--success)' : r.match === false ? 'var(--danger)' : 'var(--warning-fg)' }}>{r.real_owner}</b>
                </div>
                {r.note && <div style={{ fontSize: 11.5, color: 'var(--ink-2)', marginTop: 6, fontStyle: 'italic' }}>{r.note}</div>}
              </div>
              <div style={{ textAlign: 'right' }}>
                <span style={{ padding: '4px 10px', borderRadius: 999, background: statusBadge.bg, color: statusBadge.fg, fontSize: 11.5, fontWeight: 700 }}>{statusBadge.label}</span>
                <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 4 }}>verificat {new Date(r.last_check).toLocaleDateString('ro-RO')}</div>
              </div>
            </div>
          );
        })}
      </Card>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// Fiscal — D112, D205, bilanț
// ═════════════════════════════════════════════════════════════
function FiscalScreen({ state, tr, lang }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title="Declarații fiscale"
        subtitle="D112 lunar · D205 anual · Bilanț · trimitere automată ANAF"
        right={<Button variant="primary" icon="sparkles">Pregătește D112 nov</Button>}
      />
      <Card style={{ background: 'linear-gradient(135deg, #F8E0D5, #F5C6A8)', border: '1px solid #A8482F' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: '#A8482F', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, flexShrink: 0 }}>🇷🇴</div>
          <div style={{ fontSize: 13.5, color: '#5C1F11', lineHeight: 1.55 }}>
            <b>Asociația ca persoană juridică:</b> Lunar — D112 pentru CAS/CASS (femeie de serviciu, electrician). Anual — D205 (venituri PFA admin) și bilanț contabil. BlocApp pregătește declarațiile, le semnează cu certificat digital, le trimite direct prin ANAF SPV. Pe scurt — asociația nu mai are nevoie de contabil extern (~3.000 RON/an economisiți).
          </div>
        </div>
      </Card>
      <Card padded={false}>
        {window.FISCAL_DECLARATIONS.map(d => {
          const cfg = d.status === 'submitted' ? { bg: '#DDF0E4', fg: '#065F46', label: '✓ Depusă' }
                    : d.status === 'draft' ? { bg: '#FEF3C7', fg: '#92400E', label: 'Draft' }
                    : { bg: '#FEE2E2', fg: '#991B1B', label: 'Întârziat' };
          return (
            <div key={d.id} style={{ padding: '16px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 56, height: 56, borderRadius: 11, background: 'var(--primary-light)', color: 'var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 14 }}>{d.type}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{d.type} — {d.period}</div>
                <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>
                  Scadență {new Date(d.deadline).toLocaleDateString('ro-RO', { day: 'numeric', month: 'short', year: 'numeric' })}
                  {d.submitted_at && <> · depusă {new Date(d.submitted_at).toLocaleDateString('ro-RO')}</>}
                </div>
                {d.note && <div style={{ fontSize: 11.5, color: 'var(--ink-2)', marginTop: 4, fontStyle: 'italic' }}>{d.note}</div>}
              </div>
              <div style={{ textAlign: 'right' }}>
                {d.amount && <div style={{ fontFamily: 'var(--font-mono)', fontSize: 14, fontWeight: 700, color: 'var(--ink)' }}>{window.fmtRON(d.amount)}</div>}
                <span style={{ padding: '3px 10px', borderRadius: 999, background: cfg.bg, color: cfg.fg, fontSize: 11, fontWeight: 700, marginTop: 4, display: 'inline-block' }}>{cfg.label}</span>
              </div>
            </div>
          );
        })}
      </Card>
    </div>
  );
}

Object.assign(window, { AuditScreen, CadastreScreen, FiscalScreen });
