// tenant.jsx — Mobile tenant app inside iPhone frame

function TenantApp({ state, tr, t: tweaks, setTweak, lang }) {
  const [screen, setScreen] = React.useState('home');
  const [payOpen, setPayOpen] = React.useState(false);
  const [emergencyOpen, setEmergencyOpen] = React.useState(false);
  const [invoiceEntry, setInvoiceEntry] = React.useState(null);
  // Pick the apartment for the logged-in tenant.
  // CURRENT_USER.apartment_id is the UUID; we map back via APT_CODE_TO_UUID (reverse).
  const myAptCode = React.useMemo(() => {
    if (window.CURRENT_USER && window.CURRENT_USER.apartment_id && window.APT_CODE_TO_UUID) {
      const aptUuid = window.CURRENT_USER.apartment_id;
      for (const [code, uuid] of Object.entries(window.APT_CODE_TO_UUID)) {
        if (uuid === aptUuid) return code;
      }
    }
    return 'a1'; // demo fallback
  }, []);
  const myApt = state.apartments.find(a => a.id === myAptCode) || state.apartments[0];
  const myStatus = state.aptStatus(myApt?.id);

  const newAnnouncements = state.announcements.filter(a => a.urgent).length;
  const myUnvoted = state.proposals.filter(p => p.status === 'active' && !p.votes?.[myApt.id]).length;

  return (
    <div style={{
      paddingTop: 80, paddingBottom: 40,
      minHeight: '100vh',
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      background: tweaks.dark
        ? 'radial-gradient(circle at 50% 30%, #2d2418 0%, #1a1612 50%)'
        : 'radial-gradient(circle at 50% 30%, #F5EBD9 0%, #FAF6F0 50%)',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 40, marginTop: 8 }}>
        {/* Phone */}
        <IOSDevice width={400} height={840} dark={tweaks.dark}>
          <div style={{
            background: tweaks.dark ? '#1a1612' : '#FAF6F0',
            minHeight: '100%', position: 'relative',
            paddingTop: 60, paddingBottom: 96,
          }}>
            {screen === 'home'    && <TenantHome    state={state} apt={myApt} status={myStatus} lang={lang} onPay={() => setPayOpen(true)} setScreen={setScreen} onEmergency={() => setEmergencyOpen(true)} onShowInvoice={setInvoiceEntry} />}
            {screen === 'meters'  && <TenantMeters  state={state} apt={myApt} lang={lang} />}
            {screen === 'issues'  && <TenantIssues  state={state} apt={myApt} lang={lang} />}
            {screen === 'aga'     && <TenantAGA     state={state} apt={myApt} lang={lang} />}
            {screen === 'vault'   && <TenantVault   state={state} apt={myApt} lang={lang} />}
            {screen === 'history' && <TenantHistory state={state} apt={myApt} lang={lang} />}
            {screen === 'profile' && <TenantProfile apt={myApt} lang={lang} />}

            <TenantTabBar screen={screen} setScreen={setScreen} lang={lang} dark={tweaks.dark} myUnvoted={myUnvoted} />
          </div>
        </IOSDevice>

        {/* Side helper */}
        <div style={{ width: 280, paddingTop: 80 }}>
          <div style={{
            padding: 18, borderRadius: 16,
            background: 'var(--surface)', border: '1px solid var(--border)',
            boxShadow: '0 1px 2px rgba(28, 22, 12, 0.04)',
          }}>
            <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, marginBottom: 6 }}>
              {lang === 'ro' ? 'Locatar' : 'Tenant'}
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)', marginBottom: 4 }}>{myApt.owner_name}</div>
            <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 14 }}>Ap. {myApt.number} · {window.BUILDING.name}</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5, marginBottom: 16 }}>
              {lang === 'ro'
                ? 'Doamna Maria, 72 ani, locuiește la parter. Nu plătește lift. Vede transparent suma și de unde vine.'
                : "Mrs. Maria, 72, lives on ground floor. Doesn't pay for lift. Sees transparent breakdown."}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {[
                { id: 'home',    label: lang === 'ro' ? 'Nota lunii' : 'Monthly bill', icon: 'home' },
                { id: 'vault',   label: lang === 'ro' ? 'Fond reparații' : 'Vault', icon: 'spark' },
                { id: 'issues',  label: lang === 'ro' ? 'Sesizări' : 'Issues', icon: 'bell' },
                { id: 'aga',     label: lang === 'ro' ? 'Hotărâri AGA' : 'AGA votes', icon: 'users', badge: myUnvoted },
                { id: 'meters',  label: lang === 'ro' ? 'Indexuri' : 'Meters', icon: 'droplet' },
                { id: 'history', label: lang === 'ro' ? 'Istoric plăți' : 'History', icon: 'list' },
                { id: 'profile', label: lang === 'ro' ? 'Profil' : 'Profile', icon: 'user' },
              ].map(i => (
                <button key={i.id} onClick={() => setScreen(i.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '8px 10px', borderRadius: 8, border: 0,
                  background: screen === i.id ? 'var(--primary-light)' : 'transparent',
                  color: screen === i.id ? 'var(--primary)' : 'var(--ink-2)',
                  fontFamily: 'inherit', fontSize: 12.5, fontWeight: 500,
                  textAlign: 'left', cursor: 'pointer',
                }}>
                  <Icon name={i.icon} size={14} />
                  <span style={{ flex: 1 }}>{i.label}</span>
                  {i.badge > 0 && (
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      minWidth: 18, height: 18, padding: '0 5px',
                      background: 'var(--primary)', color: '#fff',
                      borderRadius: 999, fontSize: 10, fontWeight: 700, fontFamily: 'var(--font-mono)',
                    }}>{i.badge}</span>
                  )}
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>

      <TenantPayModal open={payOpen} onClose={() => setPayOpen(false)} apt={myApt} status={myStatus} state={state} lang={lang} />
      <TenantEmergencyFlow open={emergencyOpen} onClose={() => setEmergencyOpen(false)} state={state} apt={myApt} lang={lang} />
      <InvoiceViewer open={!!invoiceEntry} onClose={() => setInvoiceEntry(null)} entry={invoiceEntry} expenses={state.expenses} state={state} apt={myApt} lang={lang} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Bottom tab bar
// ─────────────────────────────────────────────────────────────
function TenantTabBar({ screen, setScreen, lang, dark, myUnvoted }) {
  const items = [
    { id: 'home',    label: lang === 'ro' ? 'Acasă' : 'Home', icon: 'home' },
    { id: 'issues',  label: lang === 'ro' ? 'Sesizări' : 'Issues', icon: 'bell' },
    { id: 'aga',     label: lang === 'ro' ? 'Hotărâri' : 'Votes', icon: 'users', badge: myUnvoted },
    { id: 'meters',  label: lang === 'ro' ? 'Indexuri' : 'Meters', icon: 'droplet' },
    { id: 'profile', label: lang === 'ro' ? 'Profil' : 'Profile', icon: 'user' },
  ];
  return (
    <div style={{
      position: 'absolute', bottom: 24, left: 10, right: 10,
      padding: 6, borderRadius: 22,
      background: dark ? 'rgba(40, 33, 25, 0.85)' : 'rgba(255, 255, 255, 0.85)',
      backdropFilter: 'blur(24px) saturate(180%)',
      border: dark ? '1px solid rgba(255,255,255,0.08)' : '1px solid rgba(28, 22, 12, 0.08)',
      boxShadow: '0 8px 24px rgba(28, 22, 12, 0.12), 0 1px 0 rgba(255,255,255,0.5) inset',
      display: 'flex', justifyContent: 'space-around', gap: 2,
      zIndex: 10,
    }}>
      {items.map(i => {
        const active = screen === i.id;
        return (
          <button key={i.id} onClick={() => setScreen(i.id)} style={{
            flex: 1, padding: '7px 2px', border: 0,
            background: active ? 'var(--primary)' : 'transparent',
            color: active ? '#fff' : (dark ? '#d4c9b8' : '#3a2f1e'),
            borderRadius: 16, cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
            fontFamily: 'inherit', fontSize: 9.5, fontWeight: 600,
            transition: 'background 200ms ease, color 200ms ease',
            position: 'relative',
          }}>
            <Icon name={i.icon} size={18} stroke={active ? 2 : 1.6} />
            {i.label}
            {i.badge > 0 && (
              <span style={{
                position: 'absolute', top: 2, right: 8,
                minWidth: 16, height: 16, padding: '0 4px',
                background: 'var(--danger)', color: '#fff',
                borderRadius: 999, fontSize: 9.5, fontWeight: 700, fontFamily: 'var(--font-mono)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}>{i.badge}</span>
            )}
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Tenant Home — current month bill with breakdown
// ─────────────────────────────────────────────────────────────
function TenantHome({ state, apt, status, lang, onPay, setScreen, onEmergency, onShowInvoice }) {
  const charges = state.charges[apt.id];
  const breakdown = charges
    ? Object.entries(charges.breakdown)
        .filter(([_, v]) => (v.amount || 0) > 0.01)
        .sort((a, b) => b[1].amount - a[1].amount)
    : [];
  const excluded = charges?.excluded || {};
  const [expandedCat, setExpandedCat] = React.useState(null);

  // Compute per-category averages across building for comparison + anomaly detection
  const catAverages = React.useMemo(() => window.computeCategoryAverages(state), [state.charges, state.apartments]);
  // Expose on window for AnomalyAlerts component
  React.useEffect(() => { window.__catAverages = catAverages; }, [catAverages]);

  return (
    <div style={{ padding: '16px 20px 20px' }}>
      {/* Greeting */}
      <div style={{ marginBottom: 18 }}>
        <div style={{ fontSize: 14, color: 'var(--muted)', fontWeight: 500 }}>
          {lang === 'ro' ? 'Bună ziua,' : 'Hello,'}
        </div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em' }}>
          {apt.owner_name.split(' ')[1]}!
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 2 }}>
          Ap. {apt.number} · {window.BUILDING.name}
        </div>
      </div>

      {/* Main bill card */}
      <div style={{
        padding: 20, borderRadius: 20,
        background: status.status === 'paid'
          ? 'linear-gradient(135deg, #DDF0E4, #c6e6d2)'
          : 'linear-gradient(135deg, var(--primary), color-mix(in oklab, var(--primary), #000 15%))',
        color: status.status === 'paid' ? 'var(--success)' : '#fff',
        marginBottom: 18,
        boxShadow: '0 8px 24px color-mix(in oklab, var(--primary), transparent 80%)',
      }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 12 }}>
          <div>
            <div style={{ fontSize: 11.5, opacity: 0.8, textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
              {lang === 'ro' ? 'Noiembrie 2025' : 'November 2025'}
            </div>
            <div style={{ fontSize: 11.5, opacity: 0.75, marginTop: 2 }}>
              {lang === 'ro' ? 'Scadență 25 noiembrie' : 'Due Nov 25'}
            </div>
          </div>
          {status.status === 'paid' && (
            <div style={{
              padding: '4px 10px', borderRadius: 999,
              background: 'rgba(255,255,255,0.5)', fontSize: 11.5, fontWeight: 600,
              color: 'var(--success)',
            }}>✓ {lang === 'ro' ? 'Achitat' : 'Paid'}</div>
          )}
        </div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 44, fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 1 }}>
          {window.fmtRONshort(status.due)}
          <span style={{ fontSize: 22, opacity: 0.7, marginLeft: 6 }}>RON</span>
        </div>
        {status.paid > 0 && status.status !== 'paid' && (
          <div style={{ fontSize: 12.5, opacity: 0.85, marginTop: 8, fontFamily: 'var(--font-mono)' }}>
            {lang === 'ro' ? 'Plătit' : 'Paid'}: {window.fmtRON(status.paid)} · {lang === 'ro' ? 'Rest' : 'Balance'}: {window.fmtRON(status.balance)}
          </div>
        )}
        {status.status !== 'paid' && (
          <button onClick={onPay} style={{
            width: '100%', marginTop: 16,
            padding: '14px', borderRadius: 14,
            background: 'rgba(255,255,255,0.95)', color: 'var(--primary)',
            border: 0, cursor: 'pointer',
            fontFamily: 'inherit', fontSize: 15, fontWeight: 700,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            boxShadow: '0 4px 12px rgba(28, 22, 12, 0.1)',
          }}>
            <Icon name="check" size={18} stroke={2.2} />
            {lang === 'ro' ? 'Plătește online' : 'Pay online'}
          </button>
        )}
      </div>

      {/* 🚨 Emergency button */}
      <div style={{ marginBottom: 16 }}>
        <TenantEmergencyButton onOpen={onEmergency} />
      </div>

      {/* Anomaly alerts */}
      <AnomalyAlerts charges={charges} aptId={apt.id} lang={lang} averages={catAverages} onExplain={(catId) => {
        const entry = charges?.breakdown[catId];
        if (entry) onShowInvoice(entry);
      }} />

      {/* Breakdown */}
      <div style={{
        padding: 18, borderRadius: 16,
        background: 'var(--surface)', border: '1px solid var(--border)',
        marginBottom: 16,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>
            {lang === 'ro' ? `De ce ${window.fmtRONshort(status.due)} RON?` : `Why ${window.fmtRONshort(status.due)} RON?`}
          </div>
          <div style={{ fontSize: 10.5, color: 'var(--muted)', fontWeight: 500 }}>
            {lang === 'ro' ? 'Apasă pe orice linie' : 'Tap any line'}
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {breakdown.map(([catId, entry]) => {
            const cat = entry.category;
            const amt = entry.amount;
            const pct = (amt / status.due) * 100;
            const isExpanded = expandedCat === catId;
            const catAvg = catAverages[catId]?.avg || 0;
            return (
              <div key={catId} style={{
                borderRadius: 10,
                background: isExpanded ? 'var(--surface-2)' : 'transparent',
                transition: 'background 200ms ease',
              }}>
                <button onClick={() => setExpandedCat(isExpanded ? null : catId)}
                  aria-label={`${cat.name}, ${window.fmtRON(amt)}, ${isExpanded ? 'restrânge' : 'extinde'} detalii`}
                  style={{
                  width: '100%', padding: '10px 8px', border: 0, background: 'transparent',
                  cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
                  display: 'flex', alignItems: 'center', gap: 10,
                }}>
                  <div style={{
                    width: 30, height: 30, borderRadius: 8, fontSize: 14,
                    background: cat.color + '22', color: cat.color,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0,
                  }}>{cat.icon}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 6, marginBottom: 4 }}>
                      <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)', minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{cat.name}</span>
                      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
                        <ComparisonBadge amount={amt} avg={catAvg} small />
                        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{window.fmtRON(amt)}</span>
                      </div>
                    </div>
                    <div style={{ height: 3, background: 'var(--neutral-bg)', borderRadius: 999, overflow: 'hidden' }}>
                      <div style={{ width: `${pct}%`, height: '100%', background: cat.color, transition: 'width 800ms ease' }} />
                    </div>
                  </div>
                  <Icon name={isExpanded ? 'chevDown' : 'chevRight'} size={14} style={{ color: 'var(--muted)', flexShrink: 0 }} />
                </button>
                {isExpanded && (
                  <div style={{
                    padding: '4px 14px 14px 48px',
                    fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.6,
                  }}>
                    <div style={{ fontFamily: 'var(--font-mono)', background: 'var(--surface)', padding: '8px 10px', borderRadius: 8, color: 'var(--ink)', fontSize: 11, marginBottom: 6 }}>
                      {entry.formula}
                    </div>
                    <div style={{ fontSize: 11.5, color: 'var(--muted)', marginBottom: 10 }}>
                      ℹ {cat.why}
                    </div>
                    <button onClick={(e) => { e.stopPropagation(); onShowInvoice(entry); }} style={{
                      width: '100%', padding: '8px 12px', borderRadius: 8,
                      background: 'var(--primary)', color: '#fff', border: 0, cursor: 'pointer',
                      fontFamily: 'inherit', fontSize: 12, fontWeight: 600,
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                    }}>
                      <Icon name="eye" size={13} stroke={2.2} />
                      {lang === 'ro' ? 'Vezi facturi + comparare cu vecinii' : 'See invoices + compare with neighbors'}
                    </button>
                  </div>
                )}
              </div>
            );
          })}

          {/* Excluded categories — transparency: show what you DON'T pay */}
          {Object.keys(excluded).length > 0 && (
            <div style={{ marginTop: 8, paddingTop: 12, borderTop: '1px dashed var(--border)' }}>
              <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600, marginBottom: 8, padding: '0 8px' }}>
                {lang === 'ro' ? 'Nu plătești' : "You don't pay"}
              </div>
              {Object.entries(excluded).map(([catId, reason]) => {
                const cat = window.CATEGORIES.find(c => c.id === catId);
                if (!cat) return null;
                return (
                  <div key={catId} style={{
                    padding: '8px 8px',
                    display: 'flex', alignItems: 'center', gap: 10,
                    opacity: 0.65,
                  }}>
                    <div style={{
                      width: 26, height: 26, borderRadius: 7, fontSize: 12,
                      background: 'var(--neutral-bg)', color: 'var(--muted)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>{cat.icon}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--ink-2)' }}>
                        <span style={{ textDecoration: 'line-through', color: 'var(--muted)' }}>{cat.name}</span>
                      </div>
                      <div style={{ fontSize: 10.5, color: 'var(--muted)', marginTop: 1 }}>{reason}</div>
                    </div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--muted)' }}>0,00</div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* Quick info */}
      <div style={{
        padding: 14, borderRadius: 14,
        background: 'var(--surface-2)',
        display: 'flex', alignItems: 'center', gap: 12, fontSize: 12.5, color: 'var(--ink-2)',
      }}>
        <Icon name="info" size={16} style={{ color: 'var(--muted)', flexShrink: 0 }} />
        <div>
          {lang === 'ro'
            ? 'Sumele pe consum (apă, gaze) sunt calculate pe baza indexurilor introduse luna trecută.'
            : 'Consumption amounts (water, gas) are based on meter readings from last month.'}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Tenant Meters — submit current readings
// ─────────────────────────────────────────────────────────────
function TenantMeters({ state, apt, lang }) {
  const r = state.readings[apt.id];
  const [coldNew, setColdNew] = React.useState(r.cold_curr.toFixed(3));
  const [hotNew, setHotNew] = React.useState(r.hot_curr.toFixed(3));
  const [submitted, setSubmitted] = React.useState(false);
  const toast = useToast();

  const coldDelta = parseFloat(coldNew) - r.cold_prev;
  const hotDelta = parseFloat(hotNew) - r.hot_prev;

  const submit = async () => {
    const newReading = {
      cold_prev: r.cold_prev, cold_curr: parseFloat(coldNew),
      hot_prev: r.hot_prev,  hot_curr: parseFloat(hotNew),
    };
    if (window.blocLive) {
      try {
        await window.blocLive.upsertMeter({ apt: apt.id, ...newReading });
        state.setReadings(prev => ({ ...prev, [apt.id]: { ...prev[apt.id], ...newReading } }));
        setSubmitted(true);
        toast(lang === 'ro' ? 'Indexuri trimise. Mulțumim!' : 'Readings sent. Thank you!');
        setTimeout(() => setSubmitted(false), 2000);
      } catch (err) {
        toast((lang === 'ro' ? 'Eroare: ' : 'Error: ') + err.message, 'error');
      }
    } else {
      state.setReadings(prev => ({ ...prev, [apt.id]: { ...prev[apt.id], ...newReading } }));
      setSubmitted(true);
      toast(lang === 'ro' ? 'Indexuri trimise. Mulțumim!' : 'Readings sent. Thank you!');
      setTimeout(() => setSubmitted(false), 2000);
    }
  };

  return (
    <div style={{ padding: '16px 20px 20px' }}>
      <div style={{ marginBottom: 18 }}>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)', margin: 0, letterSpacing: '-0.01em' }}>
          {lang === 'ro' ? 'Indexuri apometre' : 'Meter readings'}
        </h2>
        <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 4 }}>
          {lang === 'ro' ? 'Trimite citirea până pe 20 ale lunii' : 'Submit by the 20th of the month'}
        </div>
      </div>

      <MeterCard
        icon="💧" color="#3B82F6"
        label={lang === 'ro' ? 'Apă rece' : 'Cold water'}
        prev={r.cold_prev} curr={coldNew} setCurr={setColdNew}
        delta={coldDelta} cost={coldDelta * window.UTIL_COST.cold}
        lang={lang}
      />
      <MeterCard
        icon="🚿" color="#EF4444"
        label={lang === 'ro' ? 'Apă caldă' : 'Hot water'}
        prev={r.hot_prev} curr={hotNew} setCurr={setHotNew}
        delta={hotDelta} cost={hotDelta * window.UTIL_COST.hot}
        lang={lang}
      />

      <button onClick={submit} style={{
        width: '100%', marginTop: 12,
        padding: '16px', borderRadius: 14,
        background: 'var(--primary)', color: '#fff', border: 0, cursor: 'pointer',
        fontFamily: 'inherit', fontSize: 15, fontWeight: 700,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        boxShadow: '0 4px 12px color-mix(in oklab, var(--primary), transparent 70%)',
        transition: 'transform 120ms ease',
      }}
      onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.98)'}
      onMouseUp={(e) => e.currentTarget.style.transform = 'scale(1)'}
      >
        <Icon name={submitted ? 'check' : 'arrowRight'} size={18} stroke={2.2} />
        {submitted ? (lang === 'ro' ? 'Trimis!' : 'Sent!') : (lang === 'ro' ? 'Trimite indexurile' : 'Submit readings')}
      </button>

      {/* History */}
      <div style={{ marginTop: 24 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 10 }}>
          {lang === 'ro' ? 'Citiri anterioare' : 'Previous readings'}
        </div>
        {[
          { month: lang === 'ro' ? 'Octombrie 2025' : 'Oct 2025', cold: r.cold_prev, hot: r.hot_prev, ts: '20 oct' },
          { month: lang === 'ro' ? 'Septembrie 2025' : 'Sep 2025', cold: r.cold_prev - 4.2, hot: r.hot_prev - 1.6, ts: '18 sep' },
          { month: lang === 'ro' ? 'August 2025' : 'Aug 2025', cold: r.cold_prev - 8.1, hot: r.hot_prev - 3.2, ts: '19 aug' },
        ].map((h, i) => (
          <div key={i} style={{
            padding: '12px 14px', marginBottom: 6, borderRadius: 12,
            background: 'var(--surface)', border: '1px solid var(--border)',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            fontSize: 12.5,
          }}>
            <div>
              <div style={{ fontWeight: 600, color: 'var(--ink)' }}>{h.month}</div>
              <div style={{ fontSize: 11, color: 'var(--muted)' }}>{lang === 'ro' ? 'Trimis pe' : 'Sent on'} {h.ts}</div>
            </div>
            <div style={{ display: 'flex', gap: 12, fontFamily: 'var(--font-mono)', fontSize: 11.5 }}>
              <span style={{ color: '#3B82F6' }}>💧 {h.cold.toFixed(2)}</span>
              <span style={{ color: '#EF4444' }}>🚿 {h.hot.toFixed(2)}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function MeterCard({ icon, color, label, prev, curr, setCurr, delta, cost, lang }) {
  return (
    <div style={{
      padding: 16, borderRadius: 16, marginBottom: 12,
      background: 'var(--surface)', border: '1px solid var(--border)',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
        <div style={{ fontSize: 28 }}>{icon}</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{label}</div>
          <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>
            {lang === 'ro' ? 'Citirea anterioară' : 'Previous reading'}: <span style={{ fontFamily: 'var(--font-mono)' }}>{prev.toFixed(3)}</span> m³
          </div>
        </div>
      </div>
      <input
        type="number" step="0.001"
        value={curr}
        onChange={(e) => setCurr(e.target.value)}
        style={{
          width: '100%', padding: '14px 16px', borderRadius: 12,
          border: '2px solid var(--border)', background: 'var(--surface-2)',
          fontFamily: 'var(--font-mono)', fontSize: 22, fontWeight: 700, color: 'var(--ink)',
          outline: 'none', textAlign: 'center',
          letterSpacing: '0.02em',
          boxSizing: 'border-box',
        }}
        onFocus={(e) => { e.target.style.borderColor = color; e.target.style.background = 'var(--surface)'; }}
        onBlur={(e) => { e.target.style.borderColor = 'var(--border)'; e.target.style.background = 'var(--surface-2)'; }}
      />
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10, fontSize: 12 }}>
        <div>
          <span style={{ color: 'var(--muted)' }}>{lang === 'ro' ? 'Consum' : 'Consumption'}: </span>
          <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, color: color }}>+{delta.toFixed(3)} m³</span>
        </div>
        <div>
          <span style={{ color: 'var(--muted)' }}>≈ </span>
          <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, color: 'var(--ink)' }}>{window.fmtRON(cost)}</span>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Tenant History
// ─────────────────────────────────────────────────────────────
function TenantHistory({ state, apt, lang }) {
  const all = window.TENANT_HISTORY;
  const total = all.reduce((s, h) => s + h.amount, 0);

  return (
    <div style={{ padding: '16px 20px 20px' }}>
      <div style={{ marginBottom: 18 }}>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)', margin: 0, letterSpacing: '-0.01em' }}>
          {lang === 'ro' ? 'Istoric plăți' : 'Payment history'}
        </h2>
        <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 4 }}>
          {lang === 'ro' ? `${all.length} luni · total plătit ${window.fmtRON(total)}` : `${all.length} months · total paid ${window.fmtRON(total)}`}
        </div>
      </div>

      {/* Mini chart */}
      <div style={{
        padding: 16, borderRadius: 16, marginBottom: 16,
        background: 'var(--surface)', border: '1px solid var(--border)',
      }}>
        <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 10, textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>
          {lang === 'ro' ? 'Ultimele 8 luni' : 'Last 8 months'}
        </div>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 80 }}>
          {[...all].reverse().map((h, i) => {
            const max = Math.max(...all.map(x => x.amount));
            const ratio = h.amount / max;
            return (
              <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                <div style={{
                  width: '100%', height: `${ratio * 100}%`, minHeight: 4,
                  background: i === all.length - 1 ? 'var(--primary)' : 'var(--primary-light)',
                  borderRadius: '4px 4px 0 0',
                  transition: 'height 600ms ease',
                  transitionDelay: (i * 60) + 'ms',
                }} />
                <div style={{ fontSize: 9.5, color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>
                  {h.month.split(' ')[0].slice(0, 3)}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* List */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {all.map((h, i) => (
          <div key={h.id} style={{
            padding: 14, borderRadius: 14,
            background: 'var(--surface)', border: '1px solid var(--border)',
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: 10,
              background: 'var(--success-bg)', color: 'var(--success-fg)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <Icon name="check" size={20} stroke={2.2} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 600, fontSize: 13.5, color: 'var(--ink)' }}>{h.month}</div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>
                {h.method} · {h.paid_at}
              </div>
            </div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 14.5, fontWeight: 700, color: 'var(--ink)' }}>
              {window.fmtRON(h.amount)}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Tenant Profile
// ─────────────────────────────────────────────────────────────
function TenantProfile({ apt, lang }) {
  return (
    <div style={{ padding: '16px 20px 20px' }}>
      <div style={{ marginBottom: 18, textAlign: 'center' }}>
        <div style={{
          width: 80, height: 80, borderRadius: 999,
          background: 'var(--accent)', color: '#fff',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 28,
          marginBottom: 12,
        }}>{apt.owner_name.split(' ').map(p => p[0]).join('').slice(0, 2)}</div>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 21, fontWeight: 600, color: 'var(--ink)', margin: 0, letterSpacing: '-0.01em' }}>{apt.owner_name}</h2>
        <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 4 }}>Ap. {apt.number} · {window.BUILDING.name}</div>
      </div>

      <div style={{ background: 'var(--surface)', borderRadius: 14, border: '1px solid var(--border)', padding: '4px 0', marginBottom: 14 }}>
        <ProfileRow icon="phone" label={lang === 'ro' ? 'Telefon' : 'Phone'} value={apt.owner_phone} />
        <ProfileRow icon="mail" label="Email" value="maria.ionescu@email.ro" />
        <ProfileRow icon="building" label={lang === 'ro' ? 'Adresă' : 'Address'} value={`${window.BUILDING.address}, Ap. ${apt.number}`} />
        <ProfileRow icon="users" label={lang === 'ro' ? 'Persoane' : 'Persons'} value={String(apt.persons_count)} last />
      </div>

      <div style={{ background: 'var(--surface)', borderRadius: 14, border: '1px solid var(--border)', padding: '4px 0', marginBottom: 14 }}>
        <div style={{ padding: '12px 18px', fontSize: 12, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>
          {lang === 'ro' ? 'Administrator scară' : 'Building admin'}
        </div>
        <ProfileRow icon="user" label={window.BUILDING.admin_name} value={lang === 'ro' ? 'Administrator' : 'Admin'} />
        <ProfileRow icon="phone" label={window.BUILDING.admin_phone} value={lang === 'ro' ? 'Apel direct' : 'Call'} last />
      </div>

      <button style={{
        width: '100%', padding: '14px',
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 14, cursor: 'pointer',
        color: 'var(--danger)', fontFamily: 'inherit', fontSize: 14, fontWeight: 600,
      }}>{lang === 'ro' ? 'Ieșire din cont' : 'Sign out'}</button>
    </div>
  );
}

function ProfileRow({ icon, label, value, last }) {
  return (
    <div style={{
      padding: '14px 18px',
      borderBottom: last ? 'none' : '1px solid var(--border)',
      display: 'flex', alignItems: 'center', gap: 14,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 8,
        background: 'var(--surface-2)', color: 'var(--muted)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={icon} size={16} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink)' }}>{label}</div>
        <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>{value}</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Tenant payment modal (online Stripe-style)
// ─────────────────────────────────────────────────────────────
function TenantPayModal({ open, onClose, apt, status, state, lang }) {
  const [step, setStep] = React.useState(0); // 0: review, 1: card, 2: success
  const [card, setCard] = React.useState({ num: '4242 4242 4242 4242', exp: '12/27', cvc: '123' });
  const [processing, setProcessing] = React.useState(false);
  const toast = useToast();

  React.useEffect(() => { if (open) setStep(0); }, [open]);

  const pay = async () => {
    setProcessing(true);
    await new Promise(r => setTimeout(r, 1600));
    state.setPayments(ps => [...ps, {
      apt: apt.id, amount_paid: status.balance, method: 'online',
      date: new Date().toISOString().slice(0, 10), reference: 'pi_3Q' + Math.random().toString(36).slice(2, 8),
    }]);
    setProcessing(false);
    setStep(2);
    setTimeout(() => { onClose(); toast(lang === 'ro' ? 'Plată reușită' : 'Payment successful'); }, 1600);
  };

  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 80,
      background: 'rgba(28, 22, 12, 0.55)', backdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: 380, background: 'var(--surface)', borderRadius: 22,
        padding: 24,
        boxShadow: '0 24px 60px rgba(28, 22, 12, 0.3)',
        }}>
        {step === 0 && (
          <>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', margin: 0 }}>
                {lang === 'ro' ? 'Plată online' : 'Pay online'}
              </h3>
              <button onClick={onClose} style={{ background: 'transparent', border: 0, cursor: 'pointer', color: 'var(--muted)' }}>
                <Icon name="x" size={18} />
              </button>
            </div>
            <div style={{ textAlign: 'center', padding: '24px 12px' }}>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
                {lang === 'ro' ? 'De plătit' : 'Amount due'}
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 48, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.03em', lineHeight: 1, marginTop: 6 }}>
                {window.fmtRONshort(status.balance)}
                <span style={{ fontSize: 22, color: 'var(--muted)', marginLeft: 6 }}>RON</span>
              </div>
              <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 8 }}>
                Ap. {apt.number} · {lang === 'ro' ? 'Noiembrie 2025' : 'November 2025'}
              </div>
            </div>
            <Button variant="primary" full size="lg" onClick={() => setStep(1)} icon="arrowRight">
              {lang === 'ro' ? 'Continuă' : 'Continue'}
            </Button>
            <div style={{ marginTop: 12, fontSize: 11, color: 'var(--muted)', textAlign: 'center' }}>
              🔒 {lang === 'ro' ? 'Procesat de Stripe · 0% comision pentru locatari' : 'Processed by Stripe · 0% fee for tenants'}
            </div>
          </>
        )}

        {step === 1 && (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
              <button onClick={() => setStep(0)} style={{ background: 'transparent', border: 0, cursor: 'pointer', color: 'var(--muted)' }}>
                <Icon name="arrowLeft" size={18} />
              </button>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', margin: 0, flex: 1 }}>
                {lang === 'ro' ? 'Date card' : 'Card details'}
              </h3>
            </div>

            <Field label={lang === 'ro' ? 'Număr card' : 'Card number'}>
              <Input value={card.num} onChange={(v) => setCard(c => ({ ...c, num: v }))} mono />
            </Field>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 12 }}>
              <Field label={lang === 'ro' ? 'Expirare' : 'Expiry'}>
                <Input value={card.exp} onChange={(v) => setCard(c => ({ ...c, exp: v }))} mono />
              </Field>
              <Field label="CVC">
                <Input value={card.cvc} onChange={(v) => setCard(c => ({ ...c, cvc: v }))} mono />
              </Field>
            </div>

            <Button variant="primary" full size="lg" onClick={pay} disabled={processing} style={{ marginTop: 18 }}>
              {processing ? (
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ display: 'inline-block', width: 16, height: 16, border: '2px solid #fff', borderTopColor: 'transparent', borderRadius: 999, animation: 'spin 800ms linear infinite' }} />
                  {lang === 'ro' ? 'Se procesează...' : 'Processing...'}
                </span>
              ) : (
                <span>{lang === 'ro' ? `Plătește ${window.fmtRON(status.balance)}` : `Pay ${window.fmtRON(status.balance)}`}</span>
              )}
            </Button>
          </>
        )}

        {step === 2 && (
          <div style={{ textAlign: 'center', padding: '32px 12px' }}>
            <div style={{
              width: 80, height: 80, borderRadius: 999,
              background: 'var(--success-bg)', color: 'var(--success)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              marginBottom: 16,
              animation: 'pop 400ms cubic-bezier(0.2, 0.9, 0.3, 1.6)',
            }}>
              <Icon name="check" size={42} stroke={2.5} />
            </div>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600, color: 'var(--ink)', margin: 0 }}>
              {lang === 'ro' ? 'Plată reușită!' : 'Payment successful!'}
            </h3>
            <p style={{ fontSize: 14, color: 'var(--muted)', margin: '8px 0 0' }}>
              {lang === 'ro' ? `${window.fmtRON(status.balance)} a fost încasată.` : `${window.fmtRON(status.balance)} has been received.`}
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

window.TenantApp = TenantApp;
