// access.jsx — Acces apartament 24h (locatari autorizează intrare în absență)

function AccessScreen({ state, tr, lang }) {
  // Mock: 2 active grants, 1 pending request, 2 historic
  const [grants, setGrants] = React.useState([
    {
      id: 'ag_1', apt_id: 'a4', status: 'active', granted_at: '2025-11-14T10:00:00',
      expires_at: '2025-11-16T22:00:00',
      reason: 'Reparație țeavă subsol — autorizat acces în debara',
      contractor: 'Vasile Pop (Instalator)', pin: '4827',
      witnesses: ['a3', 'a5'], events: [
        { ts: '2025-11-14T10:00:00', text: 'Cerere admin → Constantinescu Ion (Ap. 4)', actor: 'admin' },
        { ts: '2025-11-14T10:14:00', text: 'Aprobat de proprietar prin app', actor: 'tenant' },
        { ts: '2025-11-14T14:32:00', text: 'PIN 4827 generat. Vecinii Ap.3, 5 notificați ca martori.', actor: 'system' },
      ],
    },
    {
      id: 'ag_2', apt_id: 'a8', status: 'pending', requested_at: '2025-11-15T09:42:00',
      reason: 'Verificare ISCIR hidrofor — necesită acces la racord apartament 8',
      contractor: 'ISCIR Inspector', expires_at: null,
      events: [
        { ts: '2025-11-15T09:42:00', text: 'Cerere admin → Tudorescu Mihai (Ap. 8)', actor: 'admin' },
        { ts: '2025-11-15T09:42:00', text: 'Notificare push trimisă · WhatsApp · SMS', actor: 'system' },
      ],
    },
    {
      id: 'ag_3', apt_id: 'a7', status: 'completed', granted_at: '2025-10-12T08:00:00',
      completed_at: '2025-10-12T11:30:00',
      reason: 'Termopan crăpat — schimbare urgentă în absență (proprietar la mare)',
      contractor: 'GeamSoft SRL',
      events: [
        { ts: '2025-10-12T08:00:00', text: 'Cerere admin', actor: 'admin' },
        { ts: '2025-10-12T08:14:00', text: 'Aprobat (proprietar absent — autoritate generală)', actor: 'tenant' },
        { ts: '2025-10-12T09:00:00', text: 'Acces foto „înainte"', actor: 'contractor' },
        { ts: '2025-10-12T11:25:00', text: 'Lucrare finalizată. Foto „după" încărcat.', actor: 'contractor' },
        { ts: '2025-10-12T11:30:00', text: 'Apartament închis. Cheile predate adminului.', actor: 'system' },
      ],
    },
  ]);
  const [selected, setSelected] = React.useState(null);
  const toast = useToast();

  const approve = (id) => {
    setGrants(gs => gs.map(g => g.id === id ? {
      ...g, status: 'active',
      granted_at: new Date().toISOString(),
      expires_at: new Date(Date.now() + 48 * 3600 * 1000).toISOString(),
      pin: String(Math.floor(Math.random() * 9000 + 1000)),
      events: [...g.events, { ts: new Date().toISOString(), text: 'Aprobat (demo)', actor: 'tenant' }],
    } : g));
    toast('Aprobat. PIN generat, vecinii notificați.');
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title="Acces apartament 24h"
        subtitle="Locatarul aprobă în 1 click · audit complet · vecinii notificați ca martori"
        right={<Button variant="primary" icon="plus">Cerere nouă de acces</Button>}
      />

      {/* Why */}
      <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={{ flex: 1, fontSize: 13.5, color: '#1E1B4B', lineHeight: 1.55 }}>
            <b>Scenariu real:</b> conducta principală e spartă la 2 noaptea, locatarul de la Ap. 6 e plecat în Italia. Nimeni nu poate intra. <b>BlocApp Access</b> îi trimite o cerere → aprobă cu Face ID în 30 secunde → PIN unic generat pentru contractor → vecinii sunt notificați ca martori → foto „înainte" și „după" obligatorii. Audit complet, irecuzabil.
          </div>
        </div>
      </Card>

      {/* Active grants */}
      {grants.filter(g => g.status === 'active').length > 0 && (
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#059669', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10 }}>🟢 Active acum</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {grants.filter(g => g.status === 'active').map(g => <AccessCard key={g.id} g={g} state={state} onClick={() => setSelected(g)} />)}
          </div>
        </div>
      )}

      {/* Pending */}
      {grants.filter(g => g.status === 'pending').length > 0 && (
        <div>
          <div style={{ fontSize: 11, fontWeight: 700, color: '#D97706', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10 }}>⏳ Așteaptă aprobarea locatarului</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {grants.filter(g => g.status === 'pending').map(g => <AccessCard key={g.id} g={g} state={state} onClick={() => setSelected(g)} onApprove={() => approve(g.id)} />)}
          </div>
        </div>
      )}

      {/* Historic */}
      <div>
        <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10 }}>Istoric</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {grants.filter(g => g.status === 'completed').map(g => <AccessCard key={g.id} g={g} state={state} onClick={() => setSelected(g)} />)}
        </div>
      </div>

      <Drawer open={!!selected} onClose={() => setSelected(null)} title={selected ? `Acces #${selected.id}` : ''} width={580}>
        {selected && <AccessDetail g={grants.find(x => x.id === selected.id) || selected} state={state} />}
      </Drawer>
    </div>
  );
}

function AccessCard({ g, state, onClick, onApprove }) {
  const apt = state.apartments.find(a => a.id === g.apt_id);
  const statusCfg = {
    active:    { bg: '#DDF0E4', fg: '#065F46', label: 'Activ', icon: '🟢' },
    pending:   { bg: '#FEF3C7', fg: '#92400E', label: 'Așteaptă aprobare', icon: '⏳' },
    completed: { bg: 'var(--surface-2)', fg: 'var(--muted)', label: 'Finalizat', icon: '✓' },
  }[g.status];

  return (
    <Card onClick={onClick}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{
          width: 48, height: 48, borderRadius: 12, flexShrink: 0,
          background: statusCfg.bg, color: statusCfg.fg,
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22,
        }}>🔑</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>
              Ap. {apt?.number} · {apt?.owner_name}
            </span>
            <span style={{ padding: '2px 9px', borderRadius: 999, background: statusCfg.bg, color: statusCfg.fg, fontSize: 10.5, fontWeight: 700, letterSpacing: '0.04em', whiteSpace: 'nowrap' }}>{statusCfg.label}</span>
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.4 }}>{g.reason}</div>
          <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 4 }}>
            🔧 {g.contractor}
            {g.expires_at && g.status === 'active' && <> · expiră {new Date(g.expires_at).toLocaleString('ro-RO', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' })}</>}
            {g.pin && <> · PIN <b style={{ fontFamily: 'var(--font-mono)', color: 'var(--primary)' }}>{g.pin}</b></>}
          </div>
        </div>
        {g.status === 'pending' && onApprove && (
          <Button variant="primary" size="sm" icon="bell" onClick={(e) => { e.stopPropagation(); }}>Reamintește</Button>
        )}
      </div>
    </Card>
  );
}

function AccessDetail({ g, state }) {
  const apt = state.apartments.find(a => a.id === g.apt_id);

  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: 'var(--accent)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18 }}>
          {apt?.owner_name.split(' ').map(p => p[0]).join('').slice(0, 2)}
        </div>
        <div>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, 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>
      </div>

      <p style={{ fontSize: 13.5, color: 'var(--ink-2)', margin: 0, lineHeight: 1.55, padding: 14, borderRadius: 10, background: 'var(--surface-2)' }}>
        <b>Motiv:</b> {g.reason}
      </p>

      {/* PIN big */}
      {g.pin && g.status === 'active' && (
        <div style={{ padding: 20, borderRadius: 14, background: 'linear-gradient(135deg, #1F4738, #2d6a52)', color: '#fff', textAlign: 'center' }}>
          <div style={{ fontSize: 11, opacity: 0.7, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>PIN acces unic — contractor</div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 42, fontWeight: 700, letterSpacing: '0.2em' }}>{g.pin}</div>
          <div style={{ fontSize: 11, opacity: 0.7, marginTop: 8 }}>Valid 48h · single-use · log complet la fiecare folosire</div>
        </div>
      )}

      {/* Witnesses */}
      {g.witnesses && g.witnesses.length > 0 && (
        <div>
          <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 8 }}>Vecini martori notificați</div>
          <div style={{ display: 'flex', gap: 8 }}>
            {g.witnesses.map(wId => {
              const w = state.apartments.find(a => a.id === wId);
              return (
                <div key={wId} style={{ padding: '6px 12px', borderRadius: 999, background: '#DDF0E4', color: '#065F46', fontSize: 12, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                  ✓ Ap. {w?.number} — {w?.owner_name.split(' ')[1]}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Audit trail */}
      <div>
        <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 10 }}>Audit trail</div>
        <div style={{ position: 'relative', paddingLeft: 24 }}>
          <div style={{ position: 'absolute', left: 11, top: 6, bottom: 6, width: 2, background: 'var(--border)' }} />
          {g.events.map((ev, i) => {
            const colors = {
              admin: { bg: '#D1FAE5', fg: '#059669' },
              tenant: { bg: '#E7E7FA', fg: '#5B5DD3' },
              contractor: { bg: '#FEF3C7', fg: '#D97706' },
              system: { bg: '#F3F4F6', fg: '#6B7280' },
            }[ev.actor];
            return (
              <div key={i} style={{ position: 'relative', marginBottom: 12 }}>
                <div style={{
                  position: 'absolute', left: -18, top: 0,
                  width: 24, height: 24, borderRadius: 999,
                  background: colors.bg, color: colors.fg,
                  border: '2px solid var(--surface)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11,
                }}>{ev.actor === 'admin' ? '👤' : ev.actor === 'tenant' ? '🏠' : ev.actor === 'contractor' ? '🔧' : '⚙️'}</div>
                <div style={{ fontSize: 11, color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>
                  {new Date(ev.ts).toLocaleString('ro-RO', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })}
                </div>
                <div style={{ fontSize: 13, color: 'var(--ink)', lineHeight: 1.45, marginTop: 2 }}>{ev.text}</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Photos before/after */}
      {g.status === 'completed' && (
        <div>
          <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 8 }}>Fotografii înainte / după</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <StripedPlaceholder ratio="4/3" label='ÎNAINTE · 09:01' />
            <StripedPlaceholder ratio="4/3" label='DUPĂ · 11:25' />
          </div>
        </div>
      )}
    </div>
  );
}

window.AccessScreen = AccessScreen;
