// compliance.jsx — Calendar verificări obligatorii (ISCIR / DSP / PSI / asigurare)

function ComplianceScreen({ state, tr, lang }) {
  const [selected, setSelected] = React.useState(null);
  const items = window.COMPLIANCE_ITEMS.map(i => ({ ...i, _status: window.complianceStatus(i) }));

  // Sort by urgency: expired → urgent → expiring → valid
  const sortOrder = { expired: 0, urgent: 1, expiring: 2, valid: 3 };
  items.sort((a, b) => sortOrder[a._status.state] - sortOrder[b._status.state]);

  const expired = items.filter(i => i._status.state === 'expired');
  const urgent = items.filter(i => i._status.state === 'urgent');
  const totalPenaltyRisk = expired.length + urgent.length;

  // Categories for tabs/filters
  const byCategory = {};
  items.forEach(i => {
    byCategory[i.category] = byCategory[i.category] || [];
    byCategory[i.category].push(i);
  });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title="Verificări obligatorii"
        subtitle="ISCIR · PSI · DSP · Asigurări · ANRE — calendar centralizat cu termene legale și amenzi"
        right={<Button variant="primary" icon="plus">Verificare nouă</Button>}
      />

      {/* Alert if anything expired/urgent */}
      {totalPenaltyRisk > 0 && (
        <Card style={{ background: 'linear-gradient(135deg, #FEE2E2, #FECACA)', border: '1.5px solid #DC2626', boxShadow: '0 4px 14px rgba(220, 38, 38, 0.15)' }}>
          <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
            <div style={{ width: 52, height: 52, borderRadius: 14, background: '#DC2626', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 26, flexShrink: 0, animation: 'pulse 2s ease-in-out infinite' }}>⚠️</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: '#991B1B', marginBottom: 4 }}>Atenție — risc legal</div>
              <div style={{ fontSize: 14.5, fontWeight: 700, color: '#991B1B', lineHeight: 1.3, marginBottom: 4 }}>
                {expired.length > 0 && <>{expired.length} verificări <b style={{ textDecoration: 'underline' }}>expirate</b></>}
                {expired.length > 0 && urgent.length > 0 && ' · '}
                {urgent.length > 0 && <>{urgent.length} expiră în <b>sub 30 zile</b></>}
              </div>
              <div style={{ fontSize: 12.5, color: '#7F1D1D', lineHeight: 1.5 }}>
                Răspunderea legală este personală a administratorului. Amenzi posibile cumulate: <b>peste {((expired.length + urgent.length) * 5000).toLocaleString('ro-RO')} RON</b>.
              </div>
            </div>
          </div>
        </Card>
      )}

      {/* Trust banner */}
      <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={{ flex: 1, fontSize: 13.5, color: '#0C4A6E', lineHeight: 1.55 }}>
            <b>De ce există ecranul ăsta:</b> 70% din scările de bloc din România au cel puțin o verificare expirată. Administratorul personal răspunde — amenzi între 1.000 și 30.000 RON, iar liftul/căldura pot fi sistate. BlocApp urmărește automat toate termenele și notifică cu 60, 30 și 7 zile înainte.
          </div>
        </div>
      </Card>

      {/* Compact summary stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 'var(--gap)' }}>
        <ComplianceStat label="Total verificări" value={items.length} icon="list" />
        <ComplianceStat label="Expirate" value={expired.length} icon="x" highlight={expired.length > 0 ? 'danger' : null} />
        <ComplianceStat label="Expiră curând" value={urgent.length + items.filter(i => i._status.state === 'expiring').length} icon="clock" highlight={urgent.length > 0 ? 'warning' : null} />
        <ComplianceStat label="Cost anual estimat" value={`${items.reduce((s, i) => s + (i.cost || 0), 0).toLocaleString('ro-RO')} RON`} icon="receipt" />
      </div>

      {/* Timeline view */}
      <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)' }}>
            Calendar verificări
          </h3>
          <p style={{ fontSize: 12.5, color: 'var(--muted)', margin: '4px 0 0' }}>Sortat după urgență</p>
        </div>
        <div>
          {items.map(i => <ComplianceRow key={i.id} item={i} onClick={() => setSelected(i)} />)}
        </div>
      </Card>

      <Drawer open={!!selected} onClose={() => setSelected(null)} title={selected?.title} width={600}>
        {selected && <ComplianceDetail item={selected} state={state} />}
      </Drawer>
    </div>
  );
}

function ComplianceStat({ label, value, icon, highlight }) {
  const colors = {
    danger: { bg: '#FEE2E2', fg: '#991B1B' },
    warning: { bg: '#FEF3C7', fg: '#92400E' },
  };
  const h = highlight && colors[highlight];
  return (
    <Card style={{ background: h?.bg, border: h ? `1.5px solid ${h.fg}` : '1px solid var(--border)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 40, height: 40, borderRadius: 10,
          background: h ? '#fff' : 'var(--surface-2)', color: h ? h.fg : 'var(--muted)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name={icon} size={20} />
        </div>
        <div>
          <div style={{ fontSize: 11, color: h ? h.fg : 'var(--muted)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, color: h ? h.fg : 'var(--ink)', marginTop: 2 }}>{value}</div>
        </div>
      </div>
    </Card>
  );
}

function ComplianceRow({ item, onClick }) {
  const s = item._status;
  return (
    <button onClick={onClick} style={{
      width: '100%', padding: '16px 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'}
    >
      {/* Icon */}
      <div style={{
        width: 48, height: 48, borderRadius: 12, flexShrink: 0,
        background: item.color + '22', color: item.color,
        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22,
      }}>{item.icon}</div>

      {/* Info */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>{item.title}</span>
          <span style={{ padding: '1px 7px', borderRadius: 6, background: item.color + '22', color: item.color, fontSize: 10, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{item.category}</span>
        </div>
        <div style={{ fontSize: 12, color: 'var(--muted)', lineHeight: 1.4 }}>
          {item.legal_basis}
        </div>
      </div>

      {/* Deadline */}
      <div style={{ textAlign: 'right', flexShrink: 0, minWidth: 140 }}>
        <div style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>Termen</div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13.5, fontWeight: 600, color: 'var(--ink)', marginTop: 2 }}>
          {new Date(item.valid_until).toLocaleDateString('ro-RO', { day: 'numeric', month: 'short', year: 'numeric' })}
        </div>
      </div>

      {/* Status */}
      <div style={{ flexShrink: 0, minWidth: 130, textAlign: 'right' }}>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '5px 12px', borderRadius: 999,
          background: s.bg, color: s.color,
          fontSize: 12, fontWeight: 700,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: s.color }} />
          {s.label}
        </span>
      </div>

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

function ComplianceDetail({ item, state }) {
  const s = window.complianceStatus(item);
  const toast = useToast();

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{
          width: 56, height: 56, borderRadius: 14,
          background: item.color + '22', color: item.color,
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28,
        }}>{item.icon}</div>
        <div>
          <span style={{ padding: '3px 9px', borderRadius: 6, background: item.color + '22', color: item.color, fontSize: 10.5, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{item.category}</span>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, color: 'var(--ink)', margin: '6px 0 0' }}>{item.title}</h3>
        </div>
      </div>

      <p style={{ fontSize: 13.5, color: 'var(--ink-2)', margin: 0, lineHeight: 1.55 }}>{item.description}</p>

      {/* Status big */}
      <div style={{ padding: 18, borderRadius: 14, background: s.bg }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 11, color: s.color, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>Status</div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, color: s.color, letterSpacing: '-0.01em' }}>{s.label}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 11, color: s.color, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>Expiră</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 16, fontWeight: 700, color: s.color, marginTop: 2 }}>
              {new Date(item.valid_until).toLocaleDateString('ro-RO')}
            </div>
          </div>
        </div>
      </div>

      {/* Legal + cost */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <Card style={{ background: 'var(--surface-2)', boxShadow: 'none' }}>
          <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 4 }}>Bază legală</div>
          <div style={{ fontSize: 12.5, color: 'var(--ink)', lineHeight: 1.4, fontWeight: 500 }}>{item.legal_basis}</div>
        </Card>
        <Card style={{ background: 'var(--surface-2)', boxShadow: 'none' }}>
          <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 4 }}>Cost verificare</div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 16, fontWeight: 700, color: 'var(--ink)' }}>{window.fmtRON(item.cost || 0)}</div>
        </Card>
      </div>

      {/* Penalty warning */}
      {item.penalty_if_missed && (
        <div style={{ padding: 14, borderRadius: 12, background: '#FEE2E2', border: '1px solid #DC2626' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <span style={{ fontSize: 18 }}>⚠️</span>
            <span style={{ fontWeight: 700, color: '#991B1B', fontSize: 13 }}>Dacă nu se face la termen</span>
          </div>
          <div style={{ fontSize: 12.5, color: '#991B1B', lineHeight: 1.5 }}>{item.penalty_if_missed}</div>
        </div>
      )}

      {/* Inspector */}
      {item.inspector && (
        <div>
          <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 8 }}>Inspector / furnizor</div>
          <div style={{ padding: 12, borderRadius: 10, background: 'var(--surface-2)', display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: 9, background: 'var(--primary)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 12, fontFamily: 'var(--font-display)' }}>
              {item.inspector.split(' ').map(p => p[0]).join('').slice(0, 2)}
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 500, flex: 1 }}>{item.inspector}</div>
            <Button size="sm" variant="ghost" icon="phone">Contact</Button>
          </div>
        </div>
      )}

      {/* Documents */}
      {item.documents && item.documents.length > 0 && (
        <div>
          <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 8 }}>Documente</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {item.documents.map((d, i) => (
              <div key={i} style={{ padding: '10px 12px', borderRadius: 10, background: 'var(--surface-2)', display: 'flex', alignItems: 'center', gap: 10, fontSize: 12.5 }}>
                <span style={{ fontSize: 18 }}>📄</span>
                <span style={{ flex: 1, color: 'var(--ink)', fontFamily: 'var(--font-mono)' }}>{d}</span>
                <Icon name="download" size={14} style={{ color: 'var(--muted)' }} />
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Actions */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {s.state === 'expired' || s.state === 'urgent' ? (
          <Button variant="danger" full icon="phone" onClick={() => toast('Inspector contactat — programare programată')}>Programează verificare URGENTĂ</Button>
        ) : (
          <Button variant="primary" full icon="plus" onClick={() => toast('Programare creată')}>Programează verificare</Button>
        )}
        <Button variant="secondary" full icon="bell">Setează reminder</Button>
      </div>
    </div>
  );
}

Object.assign(window, { ComplianceScreen });
