// admin-screens.jsx — Expenses, Apartments, MonthlyList, Reports

// ═════════════════════════════════════════════════════════════
// 2. Expenses Screen — list, add modal, calculate animation
// ═════════════════════════════════════════════════════════════
function ExpensesScreen({ state, tr, lang, calculating, setCalculating, setScreen }) {
  const [showAdd, setShowAdd] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const toast = useToast();

  const handleAdd = async (exp) => {
    if (window.blocLive) {
      try {
        const saved = await window.blocLive.addExpense(exp);
        state.setExpenses(es => [...es, {
          id: saved.id,
          category_id: exp.category_id,
          description: saved.description,
          supplier: saved.supplier,
          invoice_number: saved.invoice_number,
          amount: parseFloat(saved.amount),
        }]);
        toast(lang === 'ro' ? 'Cheltuială salvată' : 'Expense saved');
        setShowAdd(false);
      } catch (err) {
        toast((lang === 'ro' ? 'Eroare: ' : 'Error: ') + err.message);
      }
    } else {
      state.setExpenses(es => [...es, { ...exp, id: 'e' + Math.random().toString(36).slice(2, 8) }]);
      toast(lang === 'ro' ? 'Cheltuială adăugată' : 'Expense added');
      setShowAdd(false);
    }
  };

  const handleDelete = async (id) => {
    if (window.blocLive) {
      try {
        await window.blocLive.deleteExpense(id);
        state.setExpenses(es => es.filter(e => e.id !== id));
        toast(lang === 'ro' ? 'Cheltuială ștearsă' : 'Expense removed');
      } catch (err) {
        toast((lang === 'ro' ? 'Eroare: ' : 'Error: ') + err.message);
      }
    } else {
      state.setExpenses(es => es.filter(e => e.id !== id));
      toast(lang === 'ro' ? 'Cheltuială ștearsă' : 'Expense removed');
    }
  };

  const handleCalculate = async () => {
    setCalculating(true);
    // animated: clear charges, then re-compute after 1.6s
    state.setCharges({});
    await new Promise(r => setTimeout(r, 1800));
    state.setCharges(state.calcCharges());
    state.setListStatus('calculating');
    setCalculating(false);
    toast(lang === 'ro' ? 'Lista a fost calculată' : 'List calculated');
  };

  const handlePublish = () => {
    state.setListStatus('published');
    toast(lang === 'ro' ? 'Lista publicată' : 'List published');
    setTimeout(() => setScreen('monthly'), 600);
  };

  // Group expenses by category for visual breakdown
  const byCat = React.useMemo(() => {
    const map = {};
    state.expenses.forEach(e => {
      const cat = window.CATEGORIES.find(c => c.id === e.category_id);
      if (!cat) return;
      map[cat.id] = map[cat.id] || { cat, items: [], total: 0 };
      map[cat.id].items.push(e);
      map[cat.id].total += parseFloat(e.amount);
    });
    return Object.values(map);
  }, [state.expenses]);

  const total = state.expenses.reduce((s, e) => s + parseFloat(e.amount), 0);
  const avgPerApt = total / state.apartments.length;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title={lang === 'ro' ? 'Cheltuieli' : 'Expenses'}
        subtitle={lang === 'ro' ? 'Noiembrie 2025 · introduce facturile primite' : 'November 2025 · enter received invoices'}
        right={<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <MonthPicker lang={lang} status={state.listStatus} />
          <Button variant="primary" icon="plus" onClick={() => setShowAdd(true)}>{tr('btn.add_expense')}</Button>
        </div>}
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 'var(--gap)' }}>
        {/* Expenses list */}
        <Card padded={false}>
          <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, margin: 0, color: 'var(--ink)' }}>
              {lang === 'ro' ? 'Facturi și costuri' : 'Bills & costs'}
            </h3>
            <div style={{ fontSize: 12.5, color: 'var(--muted)' }}>
              {state.expenses.length} {lang === 'ro' ? 'cheltuieli' : 'expenses'} · {byCat.length} {lang === 'ro' ? 'categorii' : 'categories'}
            </div>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {byCat.map(g => (
              <CategoryGroup key={g.cat.id} group={g} onDelete={handleDelete} lang={lang} total={total} />
            ))}
          </div>
        </Card>

        {/* Right side: summary + actions */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap)' }}>
          <Card>
            <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, margin: 0, color: 'var(--ink)' }}>
              {lang === 'ro' ? 'Sumar lună' : 'Month summary'}
            </h4>
            <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
              <Row label={lang === 'ro' ? 'Total cheltuieli' : 'Total expenses'} value={window.fmtRON(total)} strong />
              <Row label={lang === 'ro' ? 'Apartamente active' : 'Active apartments'} value={String(state.apartments.length)} />
              <Row label={lang === 'ro' ? 'Medie / apartament' : 'Average / apt.'} value={window.fmtRON(avgPerApt)} />
              <Row label={lang === 'ro' ? 'Scadență' : 'Due date'} value="25 nov 2025" />
            </div>
          </Card>

          <Card style={{ background: 'var(--primary-light)', border: '1px solid color-mix(in oklab, var(--primary), transparent 80%)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
              <Icon name="calc" size={20} style={{ color: 'var(--primary)' }} />
              <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, margin: 0, color: 'var(--ink)' }}>
                {lang === 'ro' ? 'Generează lista de plată' : 'Generate payment list'}
              </h4>
            </div>
            <p style={{ fontSize: 12.5, color: 'var(--ink-2)', margin: '0 0 16px', lineHeight: 1.5 }}>
              {lang === 'ro'
                ? 'Distribuie cheltuielile pe apartamente conform regulilor: per persoană, m², consum apometre.'
                : 'Distributes expenses across apartments by rules: per person, m², meter consumption.'}
            </p>
            <Button variant="primary" full icon="sparkles" onClick={handleCalculate} disabled={calculating}>
              {calculating
                ? (lang === 'ro' ? 'Se calculează...' : 'Calculating...')
                : tr('btn.calculate')}
            </Button>
            {state.listStatus !== 'draft' && (
              <Button variant="success" full icon="check" onClick={handlePublish} style={{ marginTop: 8 }}>
                {tr('btn.publish')}
              </Button>
            )}
          </Card>
        </div>
      </div>

      {/* Calculate overlay */}
      {calculating && <CalculatingOverlay state={state} lang={lang} />}

      {/* Add expense modal */}
      <ExpenseModal open={showAdd} onClose={() => setShowAdd(false)} onSubmit={handleAdd} lang={lang} />
    </div>
  );
}

function Row({ label, value, strong }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, fontSize: 13.5 }}>
      <span style={{ color: 'var(--muted)' }}>{label}</span>
      <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--ink)', fontWeight: strong ? 700 : 500 }}>{value}</span>
    </div>
  );
}

function MonthPicker({ lang, status }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 10,
      background: 'var(--surface)', fontSize: 13.5, fontWeight: 600, color: 'var(--ink)',
      cursor: 'pointer',
    }}>
      <Icon name="clock" size={15} style={{ color: 'var(--muted)' }} />
      {lang === 'ro' ? 'Noiembrie 2025' : 'November 2025'}
      <StatusBadge status={status === 'published' ? 'published' : 'draft'} t={() => {}} size="sm" />
      <Icon name="chevDown" size={14} style={{ color: 'var(--muted)' }} />
    </div>
  );
}

function CategoryGroup({ group, onDelete, lang, total }) {
  const { cat, items } = group;
  const pct = (group.total / total) * 100;
  return (
    <div style={{ borderBottom: '1px solid var(--border)' }}>
      <div style={{
        padding: '14px 24px',
        background: 'var(--surface-2)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{
          width: 32, height: 32, borderRadius: 8,
          background: cat.color + '22', color: cat.color,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 16,
        }}>{cat.icon}</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--ink)' }}>{cat.name}</div>
          <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>
            {distributionLabel(cat.distribution, lang)} · {pct.toFixed(0)}% {lang === 'ro' ? 'din total' : 'of total'}
          </div>
        </div>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 700, color: 'var(--ink)' }}>
          {window.fmtRON(group.total)}
        </div>
      </div>
      {items.map(e => (
        <div key={e.id} style={{
          padding: '12px 24px 12px 68px',
          display: 'flex', alignItems: 'center', gap: 12,
          fontSize: 13,
        }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ color: 'var(--ink)', fontWeight: 500 }}>{e.description}</div>
            <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>
              {e.supplier} · {lang === 'ro' ? 'Factură' : 'Invoice'} {e.invoice_number}
            </div>
          </div>
          <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--ink)' }}>
            {window.fmtRON(e.amount)}
          </div>
          <button onClick={() => onDelete(e.id)} style={{
            background: 'transparent', border: 0, cursor: 'pointer',
            color: 'var(--muted)', padding: 6, borderRadius: 6,
          }} title="Șterge"
          onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--danger)'; e.currentTarget.style.background = 'var(--danger-bg)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--muted)'; e.currentTarget.style.background = 'transparent'; }}
          >
            <Icon name="trash" size={15} />
          </button>
        </div>
      ))}
    </div>
  );
}

function distributionLabel(d, lang) {
  const m = {
    per_apartment:   lang === 'ro' ? 'Egal / apartament' : 'Equal / apartment',
    per_person:      lang === 'ro' ? 'Per persoană' : 'Per person',
    per_sqm:         lang === 'ro' ? 'Per m²' : 'Per m²',
    per_consumption: lang === 'ro' ? 'Per consum apometru' : 'Per meter reading',
    manual:          lang === 'ro' ? 'Manual' : 'Manual',
  };
  return m[d] || d;
}

// ─────────────────────────────────────────────────────────────
// Calculating overlay — animated distribution
// ─────────────────────────────────────────────────────────────
function CalculatingOverlay({ state, lang }) {
  const [step, setStep] = React.useState(0);
  React.useEffect(() => {
    const ids = [
      setTimeout(() => setStep(1), 300),
      setTimeout(() => setStep(2), 800),
      setTimeout(() => setStep(3), 1400),
    ];
    return () => ids.forEach(clearTimeout);
  }, []);
  const steps = lang === 'ro'
    ? ['Citesc cheltuielile...', 'Distribuiesc pe apartamente...', 'Calculez sume finale...', 'Gata!']
    : ['Reading expenses...', 'Distributing to apartments...', 'Calculating final amounts...', 'Done!'];
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 95,
      background: 'rgba(28, 22, 12, 0.55)', backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
      <div style={{
        background: 'var(--surface)', borderRadius: 20, padding: 36,
        width: 460, textAlign: 'center',
        boxShadow: '0 24px 60px rgba(28, 22, 12, 0.35)',
      }}>
        <div style={{
          width: 80, height: 80, borderRadius: 999,
          background: 'var(--primary-light)', color: 'var(--primary)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 18,
          animation: 'pulse 1.2s ease-in-out infinite',
        }}>
          <Icon name="calc" size={36} stroke={2} />
        </div>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 21, fontWeight: 600, margin: 0, color: 'var(--ink)', letterSpacing: '-0.01em' }}>
          {lang === 'ro' ? 'Calculez lista lunară' : 'Calculating monthly list'}
        </h3>
        <p style={{ fontSize: 14, color: 'var(--muted)', margin: '8px 0 24px' }}>
          {steps[step]}
        </p>
        {/* Distribution beam visualization */}
        <div style={{ position: 'relative', height: 96, margin: '0 16px' }}>
          {/* Top: expense pool */}
          <div style={{
            position: 'absolute', top: 0, left: '50%', transform: 'translateX(-50%)',
            padding: '6px 14px', borderRadius: 8,
            background: 'var(--primary)', color: '#fff',
            fontSize: 12, fontWeight: 600, fontFamily: 'var(--font-mono)',
          }}>
            {window.fmtRONshort(state.totals.totalExpense)} RON
          </div>
          {/* Bottom: apartments */}
          <div style={{
            position: 'absolute', bottom: 0, left: 0, right: 0,
            display: 'flex', justifyContent: 'space-between',
          }}>
            {state.apartments.slice(0, 12).map((a, i) => (
              <div key={a.id} style={{
                width: 18, height: 18, borderRadius: 4,
                background: step >= 2 ? 'var(--accent)' : 'var(--neutral-bg)',
                color: '#fff', fontSize: 9, fontWeight: 600,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                transition: 'background 400ms ease',
                transitionDelay: (i * 30) + 'ms',
              }}>{a.number}</div>
            ))}
          </div>
          {/* SVG beams */}
          <svg viewBox="0 0 400 96" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
            {state.apartments.slice(0, 12).map((a, i) => {
              const x2 = 9 + (382 / 11) * i;
              return (
                <line key={a.id} x1="200" y1="22" x2={x2} y2="78"
                  stroke="var(--primary)" strokeWidth="1" opacity={step >= 1 ? 0.3 : 0}
                  style={{ transition: 'opacity 400ms ease', transitionDelay: (i * 40) + 'ms' }} />
              );
            })}
          </svg>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Expense modal
// ─────────────────────────────────────────────────────────────
function ExpenseModal({ open, onClose, onSubmit, lang }) {
  const [form, setForm] = React.useState({
    category_id: 'c1',
    description: '',
    supplier: '',
    invoice_number: '',
    invoice_date: '2025-11-15',
    amount: '',
  });
  const [errors, setErrors] = React.useState({});

  React.useEffect(() => {
    if (open) {
      setForm({ category_id: 'c1', description: '', supplier: '', invoice_number: '', invoice_date: '2025-11-15', amount: '' });
      setErrors({});
    }
  }, [open]);

  const submit = () => {
    const errs = {};
    if (!form.description.trim()) errs.description = true;
    if (!form.amount || parseFloat(form.amount) <= 0) errs.amount = true;
    setErrors(errs);
    if (Object.keys(errs).length) return;
    onSubmit({ ...form, amount: parseFloat(form.amount) });
  };

  const cat = window.CATEGORIES.find(c => c.id === form.category_id);

  return (
    <Modal open={open} onClose={onClose} title={lang === 'ro' ? 'Cheltuială nouă' : 'New expense'}
      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' ? 'Adaugă' : 'Add'}</Button>
      </div>}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label={lang === 'ro' ? 'Categorie' : 'Category'}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 6 }}>
            {window.CATEGORIES.slice(0, 10).map(c => (
              <button key={c.id} onClick={() => setForm(f => ({ ...f, category_id: c.id }))}
                style={{
                  padding: '10px 6px', borderRadius: 10, cursor: 'pointer',
                  background: form.category_id === c.id ? c.color + '22' : 'var(--surface-2)',
                  border: '1.5px solid ' + (form.category_id === c.id ? c.color : 'transparent'),
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                  transition: 'all 160ms ease',
                  fontFamily: 'inherit',
                }} title={c.name}>
                <div style={{ fontSize: 18 }}>{c.icon}</div>
                <div style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--ink)', textAlign: 'center', lineHeight: 1.15 }}>{c.name}</div>
              </button>
            ))}
          </div>
          <div style={{ marginTop: 8, fontSize: 12, color: 'var(--muted)' }}>
            {lang === 'ro' ? 'Distribuție:' : 'Distribution:'} <b style={{ color: 'var(--ink-2)' }}>{distributionLabel(cat.distribution, lang)}</b>
          </div>
        </Field>

        <Field label={lang === 'ro' ? 'Descriere' : 'Description'} error={errors.description}>
          <Input value={form.description} onChange={(v) => setForm(f => ({ ...f, description: v }))} placeholder={lang === 'ro' ? 'ex: Factura Aquatim oct 2025' : 'ex: Aquatim invoice oct 2025'} />
        </Field>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label={lang === 'ro' ? 'Furnizor' : 'Supplier'}>
            <Input value={form.supplier} onChange={(v) => setForm(f => ({ ...f, supplier: v }))} placeholder="Aquatim SA" />
          </Field>
          <Field label={lang === 'ro' ? 'Nr. factură' : 'Invoice no.'}>
            <Input value={form.invoice_number} onChange={(v) => setForm(f => ({ ...f, invoice_number: v }))} placeholder="AQ-2025-11..." />
          </Field>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label={lang === 'ro' ? 'Data facturii' : 'Invoice date'}>
            <Input type="date" value={form.invoice_date} onChange={(v) => setForm(f => ({ ...f, invoice_date: v }))} />
          </Field>
          <Field label={lang === 'ro' ? 'Sumă (RON)' : 'Amount (RON)'} error={errors.amount}>
            <Input type="number" value={form.amount} onChange={(v) => setForm(f => ({ ...f, amount: v }))} placeholder="540.00" mono />
          </Field>
        </div>
      </div>
    </Modal>
  );
}

function Field({ label, children, error }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)' }}>{label}</span>
      {children}
      {error && <span style={{ fontSize: 11.5, color: 'var(--danger)' }}>Câmp obligatoriu</span>}
    </label>
  );
}

function Input({ value, onChange, placeholder, type = 'text', mono }) {
  return (
    <input
      type={type} value={value} onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      style={{
        padding: '10px 14px', borderRadius: 10,
        border: '1px solid var(--border)', background: 'var(--surface)',
        fontSize: 14, fontFamily: mono ? 'var(--font-mono)' : 'inherit', color: 'var(--ink)',
        outline: 'none', transition: 'border-color 120ms ease, box-shadow 120ms ease',
      }}
      onFocus={(e) => { e.target.style.borderColor = 'var(--primary)'; e.target.style.boxShadow = '0 0 0 3px color-mix(in oklab, var(--primary), transparent 80%)'; }}
      onBlur={(e) => { e.target.style.borderColor = 'var(--border)'; e.target.style.boxShadow = 'none'; }}
    />
  );
}

window.ExpensesScreen = ExpensesScreen;
window.ExpenseModal = ExpenseModal;
window.Field = Field;
window.Input = Input;
window.distributionLabel = distributionLabel;
