// legal.jsx — Procură digitală + Transfer proprietate + Procese-verbale AGA

// ─────────────────────────────────────────────────────────────
// Mock data
// ─────────────────────────────────────────────────────────────
window.PROXIES = [
  {
    id: 'pr_1', apt_id: 'a2', principal: 'Popescu Gheorghe', proxy_id: 'a4', proxy_name: 'Constantinescu Ion',
    scope: 'AGA + plăți întreținere', valid_from: '2025-06-01', valid_until: '2026-06-01',
    status: 'active', notarized: true, notary: 'BNP Cristina Popa', doc: 'procura-2025-06-1142.pdf',
  },
  {
    id: 'pr_2', apt_id: 'a11', principal: 'Radu Bianca', proxy_id: null, proxy_name: 'Admin scară (Ion Vasile)',
    scope: 'Doar AGA · plecată în Spania', valid_from: '2025-09-01', valid_until: '2026-03-01',
    status: 'active', notarized: false, doc: null,
  },
];

window.TRANSFERS = [
  {
    id: 'tr_1', apt_id: 'a8', stage: 'pending_escrow',
    seller: 'Tudorescu Mihai', buyer: 'Vasile Andrei', price: 95000,
    arrears_due: 1342.07, sale_date: '2025-12-15',
    notary: 'BNP Cristina Popa', notary_appt: '2025-12-15T11:00:00',
    events: [
      { ts: '2025-11-10', text: 'Cerere transfer inițiată de vânzător', actor: 'seller' },
      { ts: '2025-11-12', text: 'Cumpărător confirmat — Vasile Andrei', actor: 'buyer' },
      { ts: '2025-11-14', text: 'Calcul restanțe + penalizare: 1.342,07 RON', actor: 'system' },
      { ts: '2025-11-15', text: 'Așteaptă semnătură notar pentru decont escrow', actor: 'system' },
    ],
  },
];

window.AGA_MINUTES = [
  {
    id: 'min_1', date: '2024-10-18', meeting_type: 'extraordinara',
    title: 'Schimbare administrator',
    decisions: ['Aprobat: schimbare admin (12 voturi: 9 pentru, 2 împotrivă, 1 abținere)', 'Numire Ion Vasile PFA — onorariu 600 RON/lună', 'Predarea documentelor către noul admin în 30 zile'],
    attendance: 11, total: 12, signed: true, doc: 'pv-aga-18-10-2024.pdf',
  },
  {
    id: 'min_2', date: '2025-03-12', meeting_type: 'ordinara',
    title: 'AGA ordinară — aprobare exercițiu financiar 2024',
    decisions: ['Aprobat: bilanț contabil 2024', 'Aprobat: raport cenzor (3 erori minore corectate)', 'Aprobat: regula AGA — parterul nu plătește lift'],
    attendance: 10, total: 12, signed: true, doc: 'pv-aga-12-03-2025.pdf',
  },
];

window.PAYMENT_PLANS = [
  {
    id: 'pp_1', apt_id: 'a2', proposed_at: '2025-11-15', status: 'pending_tenant_approval',
    total_debt: 2780.45, installments: 6, monthly: 463.41,
    schedule: [
      { month: 'Dec 2025', amount: 463.41, paid: false },
      { month: 'Ian 2026', amount: 463.41, paid: false },
      { month: 'Feb 2026', amount: 463.41, paid: false },
      { month: 'Mar 2026', amount: 463.41, paid: false },
      { month: 'Apr 2026', amount: 463.41, paid: false },
      { month: 'Mai 2026', amount: 463.41, paid: false },
    ],
  },
];

// ═════════════════════════════════════════════════════════════
// Legal screen — 3 tabs
// ═════════════════════════════════════════════════════════════
function LegalScreen({ state, tr, lang }) {
  const [tab, setTab] = React.useState('proxies');

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title="Legal & Documente"
        subtitle="Procuri · transferuri proprietate · procese-verbale AGA"
      />

      <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--surface-2)', borderRadius: 12, width: 'fit-content' }}>
        {[
          { id: 'proxies', label: `Procuri (${window.PROXIES.length})` },
          { id: 'transfers', label: `Transferuri (${window.TRANSFERS.length})` },
          { id: 'minutes', label: `Procese-verbale (${window.AGA_MINUTES.length})` },
          { id: 'plans', label: `Eșalonări (${window.PAYMENT_PLANS.length})` },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '8px 16px', borderRadius: 8, border: 0, cursor: 'pointer',
            background: tab === t.id ? 'var(--surface)' : 'transparent',
            color: tab === t.id ? 'var(--ink)' : 'var(--muted)',
            fontFamily: 'inherit', fontSize: 13.5, fontWeight: 600,
            boxShadow: tab === t.id ? '0 1px 2px rgba(28,22,12,0.08)' : 'none',
          }}>{t.label}</button>
        ))}
      </div>

      {tab === 'proxies' && <ProxiesTab state={state} />}
      {tab === 'transfers' && <TransfersTab state={state} />}
      {tab === 'minutes' && <MinutesTab />}
      {tab === 'plans' && <PaymentPlansTab state={state} />}
    </div>
  );
}

function ProxiesTab({ state }) {
  return (
    <>
      <Card style={{ background: 'linear-gradient(135deg, #E7E7FA, #C7D2FE)', border: '1px solid #5B5DD3' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: '#5B5DD3', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, flexShrink: 0 }}>📜</div>
          <div style={{ fontSize: 13.5, color: '#1E1B4B', lineHeight: 1.55 }}>
            <b>Procura digitală:</b> Proprietarul plecat în Italia (Spania, Germania) împuternicește un vecin sau adminul pentru AGA + plăți. Cu Face ID + carte de identitate scanată, procura e validă legal (conform Lege 287/2009 — Cod Civil art. 2018). Pentru documente notariale, integrare BNP-uri (Pop&Asoc, Camera Notarilor).
          </div>
        </div>
      </Card>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 12, marginBottom: 12 }}>
        <Button variant="primary" icon="plus">Procură nouă</Button>
      </div>
      <Card padded={false}>
        {window.PROXIES.map(p => {
          const apt = state.apartments.find(a => a.id === p.apt_id);
          return (
            <div key={p.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: '#E7E7FA', color: '#5B5DD3', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22 }}>📜</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{p.principal} (Ap. {apt?.number}) → {p.proxy_name}</div>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
                  {p.scope} · {new Date(p.valid_from).toLocaleDateString('ro-RO')} – {new Date(p.valid_until).toLocaleDateString('ro-RO')}
                  {p.notarized && <span style={{ color: '#059669', fontWeight: 600 }}> · ✓ Notarial ({p.notary})</span>}
                  {!p.notarized && <span style={{ color: '#D97706' }}> · Doar digital (Face ID + CI)</span>}
                </div>
              </div>
              <span style={{ padding: '4px 10px', borderRadius: 999, background: '#DDF0E4', color: '#065F46', fontSize: 11, fontWeight: 700 }}>Activă</span>
            </div>
          );
        })}
      </Card>
    </>
  );
}

function TransfersTab({ state }) {
  return (
    <>
      <Card style={{ background: 'linear-gradient(135deg, #FEF3C7, #FDE68A)', 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={{ fontSize: 13.5, color: '#78350F', lineHeight: 1.55 }}>
            <b>Transfer proprietate cu escrow:</b> Restanțele se decontează automat la notar din avansul cumpărătorului. Vechiul proprietar iese curat, noul proprietar primește invitația în app. <b>Singurul tool care rezolvă datoriile la transfer</b> — actualmente vânzătorii ascund restanțele.
          </div>
        </div>
      </Card>
      <div style={{ marginTop: 12 }}>
        {window.TRANSFERS.map(t => {
          const apt = state.apartments.find(a => a.id === t.apt_id);
          return (
            <Card key={t.id}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
                <div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, color: 'var(--ink)' }}>Transfer Ap. {apt?.number}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 2 }}>{t.seller} → {t.buyer} · {window.fmtRONshort(t.price)} EUR · {new Date(t.sale_date).toLocaleDateString('ro-RO')}</div>
                </div>
                <span style={{ padding: '4px 10px', borderRadius: 999, background: '#FEF3C7', color: '#92400E', fontSize: 11, fontWeight: 700 }}>Așteaptă escrow</span>
              </div>
              <div style={{ padding: 14, borderRadius: 12, background: 'var(--surface-2)', marginBottom: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>Restanțe de decontat din avans</div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 19, fontWeight: 700, color: 'var(--ink)' }}>{window.fmtRON(t.arrears_due)}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>Notar</div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{t.notary}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{new Date(t.notary_appt).toLocaleString('ro-RO', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })}</div>
                </div>
              </div>
              <div style={{ position: 'relative', paddingLeft: 22 }}>
                <div style={{ position: 'absolute', left: 10, top: 6, bottom: 6, width: 2, background: 'var(--border)' }} />
                {t.events.map((e, i) => (
                  <div key={i} style={{ position: 'relative', marginBottom: 8 }}>
                    <div style={{ position: 'absolute', left: -16, top: 0, width: 20, height: 20, borderRadius: 999, background: 'var(--surface)', border: '2px solid var(--primary)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10 }}>✓</div>
                    <span style={{ fontSize: 11, color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>{e.ts}</span>
                    <span style={{ fontSize: 12.5, color: 'var(--ink-2)', marginLeft: 10 }}>{e.text}</span>
                  </div>
                ))}
              </div>
            </Card>
          );
        })}
      </div>
    </>
  );
}

function MinutesTab() {
  return (
    <>
      <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>Procese-verbale AGA legal-valide:</b> Generate automat din voturi · cvorum verificat · semnături digitale + listă prezență. Conform Lege 196/2018 art. 64 — devin opozabile tuturor proprietarilor, inclusiv celor care nu au votat. <b>80% din PV-uri actuale sunt invalide</b> (lipsește cvorum, semnături, publicare).
          </div>
        </div>
      </Card>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 12, marginBottom: 12 }}>
        <Button variant="primary" icon="plus">Convoacă AGA</Button>
      </div>
      <Card padded={false}>
        {window.AGA_MINUTES.map(m => (
          <div key={m.id} style={{ padding: '18px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'flex-start', gap: 14 }}>
            <div style={{ width: 44, height: 56, borderRadius: 6, background: 'linear-gradient(160deg, #fff, #f5f0e6)', border: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22 }}>📄</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>{m.title}</div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2, marginBottom: 8 }}>
                {new Date(m.date).toLocaleDateString('ro-RO', { day: 'numeric', month: 'long', year: 'numeric' })} · AGA {m.meeting_type} · prezență {m.attendance}/{m.total}
              </div>
              <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.55 }}>
                {m.decisions.map((d, i) => <li key={i}>{d}</li>)}
              </ul>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'flex-end' }}>
              {m.signed && <span style={{ padding: '3px 9px', borderRadius: 999, background: '#DDF0E4', color: '#065F46', fontSize: 11, fontWeight: 700 }}>✓ Semnat digital</span>}
              <button style={{ padding: '6px 12px', borderRadius: 8, background: 'transparent', border: '1px solid var(--border)', color: 'var(--ink-2)', fontSize: 11.5, fontWeight: 600, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 4, fontFamily: 'inherit' }}>
                <Icon name="download" size={12} /> PDF
              </button>
            </div>
          </div>
        ))}
      </Card>
    </>
  );
}

function PaymentPlansTab({ state }) {
  return (
    <>
      <Card style={{ background: 'linear-gradient(135deg, #FADEDB, #FECACA)', border: '1px solid #DC2626' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: '#DC2626', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, flexShrink: 0 }}>📅</div>
          <div style={{ fontSize: 13.5, color: '#7F1D1D', lineHeight: 1.55 }}>
            <b>Plan eșalonat de plată:</b> Alternativă la acțiunea în instanță. Restanțierul își recunoaște datoria și plătește în rate · suspendă penalizările · evită instanța (cost 380 RON + 6-12 luni proces). Acord scris, semnat digital, opozabil.
          </div>
        </div>
      </Card>
      <div style={{ marginTop: 12 }}>
        {window.PAYMENT_PLANS.map(p => {
          const apt = state.apartments.find(a => a.id === p.apt_id);
          return (
            <Card key={p.id}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
                <div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, color: 'var(--ink)' }}>Plan Ap. {apt?.number} · {apt?.owner_name}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 2 }}>{window.fmtRON(p.total_debt)} în {p.installments} rate × {window.fmtRON(p.monthly)} / lună</div>
                </div>
                <span style={{ padding: '4px 10px', borderRadius: 999, background: '#FEF3C7', color: '#92400E', fontSize: 11, fontWeight: 700 }}>Așteaptă acceptarea locatarului</span>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 6 }}>
                {p.schedule.map((s, i) => (
                  <div key={i} style={{ padding: 10, borderRadius: 8, background: s.paid ? '#DDF0E4' : 'var(--surface-2)', border: '1px solid var(--border)', textAlign: 'center' }}>
                    <div style={{ fontSize: 10.5, color: 'var(--muted)', fontWeight: 600 }}>{s.month}</div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 700, color: 'var(--ink)', marginTop: 2 }}>{window.fmtRONshort(s.amount)}</div>
                    <div style={{ fontSize: 10, color: s.paid ? '#059669' : 'var(--muted)', marginTop: 2 }}>{s.paid ? '✓ Plătit' : 'Așteaptă'}</div>
                  </div>
                ))}
              </div>
            </Card>
          );
        })}
      </div>
    </>
  );
}

window.LegalScreen = LegalScreen;
