// aga.jsx — Hotărâri AGA: Admin manage + Tenant vote

const VOTE_COLORS = {
  'Pentru':    { color: '#059669', bg: '#D1FAE5' },
  'Împotrivă': { color: '#DC2626', bg: '#FADEDB' },
  'Abținere':  { color: '#6B7280', bg: '#F3F4F6' },
};

function proposalDaysLeft(p) {
  const now = new Date('2025-11-15T18:00:00');
  const end = new Date(p.deadline);
  return Math.ceil((end - now) / (1000 * 60 * 60 * 24));
}

function tallyVotes(p) {
  const totals = { 'Pentru': 0, 'Împotrivă': 0, 'Abținere': 0 };
  Object.values(p.votes || {}).forEach(v => { if (totals[v] !== undefined) totals[v]++; });
  const cast = Object.keys(p.votes || {}).length;
  return { totals, cast };
}

// ═════════════════════════════════════════════════════════════
// ADMIN — AGA management
// ═════════════════════════════════════════════════════════════
function AGAScreen({ state, tr, lang }) {
  const [tab, setTab] = React.useState('active');
  const [selected, setSelected] = React.useState(null);
  const [showCreate, setShowCreate] = React.useState(false);

  const active = state.proposals.filter(p => p.status === 'active');
  const closed = state.proposals.filter(p => p.status !== 'active');
  const items = tab === 'active' ? active : closed;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title={lang === 'ro' ? 'Hotărâri AGA' : 'AGA decisions'}
        subtitle={lang === 'ro'
          ? `${active.length} propuneri active · ${closed.length} închise`
          : `${active.length} active · ${closed.length} closed`}
        right={<Button variant="primary" icon="plus" onClick={() => setShowCreate(true)}>
          {lang === 'ro' ? 'Propunere nouă' : 'New proposal'}
        </Button>}
      />

      {/* Info banner */}
      <Card style={{ background: 'var(--primary-light)', border: '1px solid color-mix(in oklab, var(--primary), transparent 80%)' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <Icon name="info" size={20} style={{ color: 'var(--primary)', flexShrink: 0, marginTop: 2 }} stroke={2} />
          <div style={{ fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.55 }}>
            <b style={{ color: 'var(--ink)' }}>{lang === 'ro' ? 'Conform Legii 196/2018:' : 'Per Law 196/2018:'}</b>{' '}
            {lang === 'ro'
              ? 'Hotărârile pentru cheltuieli se aprobă cu jumătate + 1 din proprietari. Modificările de regulament sau cele care implică obligații financiare semnificative cer 2/3. Votul online are aceeași valoare juridică ca votul în AGA fizic dacă e prevăzut în regulament.'
              : 'Spending decisions need 50%+1. Regulation changes need 2/3.'}
          </div>
        </div>
      </Card>

      <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--surface-2)', borderRadius: 12, width: 'fit-content' }}>
        {[
          { id: 'active', label: lang === 'ro' ? `Active (${active.length})` : `Active (${active.length})` },
          { id: 'closed', label: lang === 'ro' ? `Închise (${closed.length})` : `Closed (${closed.length})` },
        ].map(tg => (
          <button key={tg.id} onClick={() => setTab(tg.id)} style={{
            padding: '8px 16px', borderRadius: 8, border: 0, cursor: 'pointer',
            background: tab === tg.id ? 'var(--surface)' : 'transparent',
            color: tab === tg.id ? 'var(--ink)' : 'var(--muted)',
            fontFamily: 'inherit', fontSize: 13.5, fontWeight: 600,
            boxShadow: tab === tg.id ? '0 1px 2px rgba(28,22,12,0.08)' : 'none',
          }}>{tg.label}</button>
        ))}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap)' }}>
        {items.map(p => <ProposalCardAdmin key={p.id} p={p} state={state} lang={lang} onClick={() => setSelected(p)} />)}
      </div>

      <Drawer open={!!selected} onClose={() => setSelected(null)} title={selected ? selected.title : ''} width={620}>
        {selected && <ProposalDetailAdmin p={state.proposals.find(x => x.id === selected.id) || selected} state={state} lang={lang} />}
      </Drawer>

      <CreateProposalModal open={showCreate} onClose={() => setShowCreate(false)} state={state} lang={lang} />
    </div>
  );
}

function ProposalCardAdmin({ p, state, lang, onClick }) {
  const { totals, cast } = tallyVotes(p);
  const daysLeft = proposalDaysLeft(p);
  const total = state.apartments.length;
  const quorumPct = (cast / p.quorum_required) * 100;
  const forPct = cast > 0 ? (totals['Pentru'] / cast) * 100 : 0;
  const isApproved = p.status === 'approved';
  const isRejected = p.status === 'rejected';

  return (
    <Card onClick={onClick}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
        <div style={{
          width: 48, height: 48, borderRadius: 12, flexShrink: 0,
          background: p.category === 'reparatie' ? '#FEF3C7' : p.category === 'fond' ? '#FADEDB' : '#E0F2FE',
          color: p.category === 'reparatie' ? '#D97706' : p.category === 'fond' ? '#A8482F' : '#0284C7',
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22,
        }}>
          {p.category === 'reparatie' ? '🔧' : p.category === 'fond' ? '💰' : p.category === 'echipament' ? '⚙️' : '📋'}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 6 }}>
            <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, color: 'var(--ink)', margin: 0, flex: 1, lineHeight: 1.3 }}>{p.title}</h4>
            {p.amount && (
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 700, color: 'var(--primary)', whiteSpace: 'nowrap' }}>
                {window.fmtRONshort(p.amount)} RON
              </div>
            )}
          </div>
          <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5, marginBottom: 12 }}>
            {p.description.slice(0, 160)}{p.description.length > 160 ? '...' : ''}
          </div>

          {p.status === 'active' && (
            <>
              {/* Vote bars */}
              <div style={{ display: 'flex', gap: 1, height: 8, borderRadius: 999, overflow: 'hidden', marginBottom: 8, background: 'var(--neutral-bg)' }}>
                {Object.entries(totals).map(([opt, n]) => {
                  if (n === 0) return null;
                  return <div key={opt} style={{ width: `${(n / total) * 100}%`, background: VOTE_COLORS[opt].color }} />;
                })}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
                <div style={{ display: 'flex', gap: 14, fontSize: 12.5, fontWeight: 600 }}>
                  <span style={{ color: '#059669' }}>✓ {totals['Pentru']}</span>
                  <span style={{ color: '#DC2626' }}>✗ {totals['Împotrivă']}</span>
                  <span style={{ color: '#6B7280' }}>~ {totals['Abținere']}</span>
                  <span style={{ color: 'var(--muted)' }}>{total - cast} {lang === 'ro' ? 'nevotați' : 'unvoted'}</span>
                </div>
                <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                  <span style={{ fontSize: 12, color: 'var(--muted)' }}>
                    {lang === 'ro' ? 'Cvorum' : 'Quorum'}: <b style={{ color: quorumPct >= 100 ? 'var(--success)' : 'var(--ink-2)' }}>{cast}/{p.quorum_required}</b>
                  </span>
                  <span style={{ fontSize: 12, color: daysLeft <= 3 ? 'var(--warning-fg)' : 'var(--muted)', fontWeight: daysLeft <= 3 ? 600 : 500 }}>
                    {daysLeft > 0 ? (lang === 'ro' ? `${daysLeft} zile rămase` : `${daysLeft} days left`) : (lang === 'ro' ? 'Expirat' : 'Expired')}
                  </span>
                </div>
              </div>
            </>
          )}
          {(isApproved || isRejected) && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{
                padding: '5px 12px', borderRadius: 999,
                background: isApproved ? 'var(--success-bg)' : 'var(--danger-bg)',
                color: isApproved ? 'var(--success-fg)' : 'var(--danger-fg)',
                fontSize: 12, fontWeight: 700,
              }}>
                {isApproved ? (lang === 'ro' ? '✓ APROBAT' : '✓ APPROVED') : (lang === 'ro' ? '✗ RESPINS' : '✗ REJECTED')}
              </div>
              <span style={{ fontSize: 12, color: 'var(--muted)' }}>
                ✓ {totals['Pentru']} · ✗ {totals['Împotrivă']} · ~ {totals['Abținere']} · {lang === 'ro' ? 'închis' : 'closed'} {p.closed_at}
              </span>
            </div>
          )}
        </div>
      </div>
    </Card>
  );
}

function ProposalDetailAdmin({ p, state, lang }) {
  const { totals, cast } = tallyVotes(p);
  const total = state.apartments.length;
  const voted = Object.entries(p.votes || {});
  const unvoted = state.apartments.filter(a => !p.votes?.[a.id]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div>
        <div style={{ fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.6 }}>{p.description}</div>
        {p.amount && (
          <div style={{ marginTop: 12, padding: 12, borderRadius: 10, background: 'var(--primary-light)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 12.5, color: 'var(--ink-2)', fontWeight: 500 }}>{lang === 'ro' ? 'Buget propus' : 'Proposed budget'}</span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 17, fontWeight: 700, color: 'var(--primary)' }}>{window.fmtRON(p.amount)}</span>
          </div>
        )}
      </div>

      {/* Big vote summary */}
      <div style={{ padding: 16, borderRadius: 14, background: 'var(--surface-2)' }}>
        <div style={{ fontSize: 12, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 12 }}>
          {lang === 'ro' ? 'Rezultat curent' : 'Current result'}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 12 }}>
          {Object.entries(totals).map(([opt, n]) => (
            <div key={opt} style={{
              padding: 12, borderRadius: 10,
              background: VOTE_COLORS[opt].bg,
              textAlign: 'center',
            }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 700, color: VOTE_COLORS[opt].color, lineHeight: 1 }}>{n}</div>
              <div style={{ fontSize: 11, fontWeight: 600, color: VOTE_COLORS[opt].color, marginTop: 4 }}>{opt}</div>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--ink-2)' }}>
          <span>{lang === 'ro' ? 'Cvorum necesar' : 'Quorum required'}: <b>{p.quorum_required}/{total}</b></span>
          <span style={{ color: cast >= p.quorum_required ? 'var(--success)' : 'var(--warning-fg)', fontWeight: 600 }}>
            {cast >= p.quorum_required ? '✓ ' : '⏳ '}
            {cast}/{p.quorum_required} {lang === 'ro' ? 'au votat' : 'voted'}
          </span>
        </div>
      </div>

      {/* Who voted what */}
      <div>
        <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 8, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
          {lang === 'ro' ? 'Cine cum a votat' : 'How each voted'}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
          {state.apartments.map(a => {
            const v = p.votes?.[a.id];
            return (
              <div key={a.id} style={{
                padding: '8px 12px', borderRadius: 8,
                background: 'var(--surface-2)',
                display: 'flex', alignItems: 'center', gap: 10,
                fontSize: 12.5,
              }}>
                <span style={{
                  fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--muted)',
                  width: 24,
                }}>{a.number}</span>
                <span style={{ flex: 1, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.owner_name}</span>
                {v ? (
                  <span style={{
                    padding: '2px 8px', borderRadius: 999,
                    background: VOTE_COLORS[v].bg, color: VOTE_COLORS[v].color,
                    fontSize: 11, fontWeight: 600,
                  }}>{v}</span>
                ) : (
                  <span style={{ fontSize: 11, color: 'var(--muted)', fontStyle: 'italic' }}>{lang === 'ro' ? 'nevotat' : 'unvoted'}</span>
                )}
              </div>
            );
          })}
        </div>
        {unvoted.length > 0 && p.status === 'active' && (
          <Button size="sm" variant="secondary" icon="mail" style={{ marginTop: 12 }}>
            {lang === 'ro' ? `Reamintește la ${unvoted.length} nevotați` : `Remind ${unvoted.length}`}
          </Button>
        )}
      </div>

      {/* Attachments */}
      {p.attachments && p.attachments.length > 0 && (
        <div>
          <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 8, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
            {lang === 'ro' ? 'Documente' : 'Documents'}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {p.attachments.map((f, i) => (
              <div key={i} style={{
                padding: '10px 14px', borderRadius: 10,
                background: 'var(--surface-2)',
                display: 'flex', alignItems: 'center', gap: 10, fontSize: 13,
              }}>
                <span style={{ fontSize: 18 }}>📄</span>
                <span style={{ flex: 1, color: 'var(--ink)' }}>{f}</span>
                <Icon name="download" size={15} style={{ color: 'var(--muted)' }} />
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function CreateProposalModal({ open, onClose, state, lang }) {
  const [title, setTitle] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const [type, setType] = React.useState('cheltuiala');
  const [amount, setAmount] = React.useState('');
  const [deadline, setDeadline] = React.useState('2025-12-15');
  const toast = useToast();

  React.useEffect(() => {
    if (open) { setTitle(''); setDesc(''); setType('cheltuiala'); setAmount(''); setDeadline('2025-12-15'); }
  }, [open]);

  const submit = () => {
    if (!title.trim() || !desc.trim()) { toast(lang === 'ro' ? 'Completează titlu și descriere' : 'Fill title + description', 'error'); return; }
    state.setProposals(ps => [{
      id: 'p' + Math.random().toString(36).slice(2, 6),
      title, description: desc, type,
      category: type === 'cheltuiala' ? 'reparatie' : 'general',
      amount: amount ? parseFloat(amount) : null,
      proposer: window.BUILDING.admin_name + ' (administrator)',
      created_at: new Date().toISOString().slice(0, 10),
      deadline,
      status: 'active',
      quorum_required: type === 'regulament' ? 9 : 7,
      options: ['Pentru', 'Împotrivă', 'Abținere'],
      votes: {},
    }, ...ps]);
    toast(lang === 'ro' ? 'Propunere creată — locatarii au fost notificați' : 'Proposal created');
    onClose();
  };

  return (
    <Modal open={open} onClose={onClose} title={lang === 'ro' ? 'Propunere nouă AGA' : 'New AGA proposal'}
      footer={<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <Button variant="secondary" onClick={onClose}>{lang === 'ro' ? 'Anulează' : 'Cancel'}</Button>
        <Button variant="primary" onClick={submit} icon="check">{lang === 'ro' ? 'Publică' : 'Publish'}</Button>
      </div>}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label={lang === 'ro' ? 'Tip hotărâre' : 'Type'}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {[
              { id: 'cheltuiala', label: lang === 'ro' ? '💰 Cheltuială (50%+1)' : '💰 Spending (50%+1)' },
              { id: 'regulament', label: lang === 'ro' ? '📋 Regulament (2/3)' : '📋 Regulation (2/3)' },
            ].map(o => (
              <button key={o.id} onClick={() => setType(o.id)} style={{
                padding: '12px', borderRadius: 10, cursor: 'pointer',
                background: type === o.id ? 'var(--primary)' : 'var(--surface-2)',
                color: type === o.id ? '#fff' : 'var(--ink)',
                border: 0, fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
              }}>{o.label}</button>
            ))}
          </div>
        </Field>
        <Field label={lang === 'ro' ? 'Titlu' : 'Title'}>
          <Input value={title} onChange={setTitle} placeholder={lang === 'ro' ? 'ex: Reabilitare termică' : 'ex: Thermal rehab'} />
        </Field>
        <Field label={lang === 'ro' ? 'Descriere completă' : 'Full description'}>
          <textarea value={desc} onChange={(e) => setDesc(e.target.value)} rows={5} placeholder={lang === 'ro' ? 'Context, oferte, motive...' : 'Context, options, reasoning...'} style={{
            padding: '10px 14px', borderRadius: 10,
            border: '1px solid var(--border)', background: 'var(--surface)',
            fontSize: 14, fontFamily: 'inherit', color: 'var(--ink)', outline: 'none',
            resize: 'vertical', minHeight: 100,
          }} />
        </Field>
        {type === 'cheltuiala' && (
          <Field label={lang === 'ro' ? 'Buget (RON)' : 'Budget (RON)'}>
            <Input type="number" value={amount} onChange={setAmount} placeholder="0.00" mono />
          </Field>
        )}
        <Field label={lang === 'ro' ? 'Termen vot' : 'Voting deadline'}>
          <Input type="date" value={deadline} onChange={setDeadline} />
        </Field>
      </div>
    </Modal>
  );
}

// ═════════════════════════════════════════════════════════════
// TENANT — Vote view
// ═════════════════════════════════════════════════════════════
function TenantAGA({ state, apt, lang }) {
  const [tab, setTab] = React.useState('active');
  const [expanded, setExpanded] = React.useState(null);
  const toast = useToast();

  const vote = (proposalId, option) => {
    state.setProposals(ps => ps.map(p => p.id === proposalId
      ? { ...p, votes: { ...p.votes, [apt.id]: option } }
      : p));
    toast(lang === 'ro' ? `Votat: ${option}` : `Voted: ${option}`);
  };

  const active = state.proposals.filter(p => p.status === 'active');
  const closed = state.proposals.filter(p => p.status !== 'active');
  const items = tab === 'active' ? active : closed;
  const myUnvoted = active.filter(p => !p.votes?.[apt.id]).length;

  return (
    <div style={{ padding: '16px 20px 100px' }}>
      <div style={{ marginBottom: 14 }}>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)', margin: 0, letterSpacing: '-0.01em' }}>
          {lang === 'ro' ? 'Hotărâri scară' : 'Decisions'}
        </h2>
        <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 4 }}>
          {myUnvoted > 0
            ? <span style={{ color: 'var(--primary)', fontWeight: 600 }}>{lang === 'ro' ? `${myUnvoted} propuneri așteaptă votul tău` : `${myUnvoted} need your vote`}</span>
            : (lang === 'ro' ? 'Toate voturile la zi' : 'All votes up to date')}
        </div>
      </div>

      <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--surface-2)', borderRadius: 12, marginBottom: 14 }}>
        {[
          { id: 'active', label: lang === 'ro' ? `Active (${active.length})` : `Active (${active.length})` },
          { id: 'closed', label: lang === 'ro' ? `Istoric (${closed.length})` : `History (${closed.length})` },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            flex: 1, padding: '8px 12px', borderRadius: 8, border: 0,
            background: tab === t.id ? 'var(--surface)' : 'transparent',
            color: tab === t.id ? 'var(--ink)' : 'var(--muted)',
            fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
            cursor: 'pointer', boxShadow: tab === t.id ? '0 1px 2px rgba(28,22,12,0.06)' : 'none',
          }}>{t.label}</button>
        ))}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {items.map(p => (
          <TenantProposalCard key={p.id}
            p={state.proposals.find(x => x.id === p.id) || p}
            apt={apt} lang={lang}
            expanded={expanded === p.id}
            onExpand={() => setExpanded(expanded === p.id ? null : p.id)}
            onVote={(opt) => vote(p.id, opt)}
            state={state}
          />
        ))}
      </div>
    </div>
  );
}

function TenantProposalCard({ p, apt, lang, expanded, onExpand, onVote, state }) {
  const myVote = p.votes?.[apt.id];
  const { totals, cast } = tallyVotes(p);
  const total = state.apartments.length;
  const daysLeft = proposalDaysLeft(p);
  const isClosed = p.status !== 'active';

  return (
    <div style={{
      padding: 16, borderRadius: 16,
      background: 'var(--surface)', border: '1px solid var(--border)',
      boxShadow: !myVote && !isClosed ? '0 0 0 1.5px var(--primary)' : 'none',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 10 }}>
        <div style={{
          width: 40, height: 40, borderRadius: 10, flexShrink: 0,
          background: p.category === 'reparatie' ? '#FEF3C7' : '#E0F2FE',
          color: p.category === 'reparatie' ? '#D97706' : '#0284C7',
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18,
        }}>{p.category === 'reparatie' ? '🔧' : p.category === 'fond' ? '💰' : p.category === 'echipament' ? '⚙️' : '📋'}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, color: 'var(--ink)', margin: 0, lineHeight: 1.3 }}>{p.title}</h4>
          {p.amount && (
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 700, color: 'var(--primary)', marginTop: 4 }}>
              {window.fmtRON(p.amount)}
            </div>
          )}
        </div>
      </div>

      <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5, marginBottom: 10 }}>
        {expanded ? p.description : (p.description.slice(0, 100) + (p.description.length > 100 ? '...' : ''))}
        {p.description.length > 100 && (
          <button onClick={onExpand} style={{ background: 'transparent', border: 0, color: 'var(--primary)', cursor: 'pointer', fontWeight: 600, padding: 0, marginLeft: 4, fontSize: 12 }}>
            {expanded ? (lang === 'ro' ? ' mai puțin' : ' less') : (lang === 'ro' ? ' citește tot' : ' read more')}
          </button>
        )}
      </div>

      {/* Vote bars */}
      <div style={{ display: 'flex', gap: 1, height: 6, borderRadius: 999, overflow: 'hidden', marginBottom: 8, background: 'var(--neutral-bg)' }}>
        {Object.entries(totals).map(([opt, n]) => n > 0 && <div key={opt} style={{ width: `${(n / total) * 100}%`, background: VOTE_COLORS[opt].color }} />)}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--muted)', marginBottom: 12 }}>
        <span>✓ {totals['Pentru']} · ✗ {totals['Împotrivă']} · ~ {totals['Abținere']}</span>
        <span style={{ color: daysLeft <= 3 && !isClosed ? 'var(--warning-fg)' : 'var(--muted)', fontWeight: 500 }}>
          {isClosed
            ? (lang === 'ro' ? 'Închis' : 'Closed')
            : (daysLeft > 0 ? (lang === 'ro' ? `${daysLeft} zile rămase` : `${daysLeft}d left`) : (lang === 'ro' ? 'Expirat' : 'Expired'))}
        </span>
      </div>

      {/* Vote buttons */}
      {!isClosed && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6 }}>
          {['Pentru', 'Împotrivă', 'Abținere'].map(opt => {
            const isMine = myVote === opt;
            return (
              <button key={opt} onClick={() => onVote(opt)} style={{
                padding: '11px 8px', borderRadius: 10,
                background: isMine ? VOTE_COLORS[opt].color : 'var(--surface-2)',
                color: isMine ? '#fff' : VOTE_COLORS[opt].color,
                border: isMine ? `1.5px solid ${VOTE_COLORS[opt].color}` : `1.5px solid ${VOTE_COLORS[opt].bg}`,
                fontFamily: 'inherit', fontSize: 13, fontWeight: 700,
                cursor: 'pointer',
                transition: 'all 160ms ease',
              }}>{opt}</button>
            );
          })}
        </div>
      )}
      {myVote && !isClosed && (
        <div style={{ marginTop: 10, fontSize: 11.5, color: 'var(--muted)', textAlign: 'center' }}>
          {lang === 'ro' ? `Votul tău: ` : `Your vote: `}<b style={{ color: VOTE_COLORS[myVote].color }}>{myVote}</b>
        </div>
      )}
      {isClosed && (
        <div style={{
          padding: '10px 14px', borderRadius: 10,
          background: p.result === 'aprobat' ? 'var(--success-bg)' : 'var(--danger-bg)',
          color: p.result === 'aprobat' ? 'var(--success-fg)' : 'var(--danger-fg)',
          fontSize: 12.5, fontWeight: 600, textAlign: 'center',
        }}>
          {p.result === 'aprobat' ? '✓ ' : '✗ '}{p.result === 'aprobat' ? (lang === 'ro' ? 'Aprobat' : 'Approved') : (lang === 'ro' ? 'Respins' : 'Rejected')}
          {myVote && <span style={{ fontWeight: 500 }}> · {lang === 'ro' ? 'tu ai votat' : 'you voted'} <b>{myVote}</b></span>}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AGAScreen, TenantAGA });
