// screens-coffee.jsx — Coffee machines tab
//
// Sub-economy that lives parallel to the main Monthly Plan ledger:
//   - Multiple machines, each with its own sales + expenses
//   - Quick-add tap bar for "+1 sold" (one tap = one cup at default price)
//   - Sheet for expenses (rent, electricity, beans, milk, cups, service, other)
//   - Big serif net-profit hero, revenue vs expenses split, daily cumulative chart
//   - Recent transactions list (mixed sales + expenses, newest first)
//
// Net profit at month end flows into Home as a single "Coffee net" income
// entry so the user can see total picture, but stays tagged so it's clear
// it's a separate sub-economy.

const COFFEE_KINDS = [
  { id: 'rent',        label: 'Наем',       icon: '🏠' },
  { id: 'electricity', label: 'Ток',        icon: '⚡' },
  { id: 'beans',       label: 'Боб',        icon: '☕' },
  { id: 'milk',        label: 'Мляко',      icon: '🥛' },
  { id: 'cups',        label: 'Чашки',      icon: '🥤' },
  { id: 'service',     label: 'Сервиз',     icon: '🔧' },
  { id: 'other',       label: 'Друго',      icon: '·' },
];
const KIND_LABEL = Object.fromEntries(COFFEE_KINDS.map(k => [k.id, k.label]));
const KIND_ICON  = Object.fromEntries(COFFEE_KINDS.map(k => [k.id, k.icon]));

function CoffeeScreen({ store, onAddExpense, onAddSale, onManageMachines }) {
  const { coffee, coffeeStats } = store;
  const machines = coffee.machines;

  if (machines.length === 0) {
    return <CoffeeEmpty onAdd={onManageMachines}/>;
  }

  // Active machine — fall back to first if invalid
  const activeMachine = machines.find(m => m.id === coffee.activeMachineId) || machines[0];

  // Filter stats by active machine
  const monthSales = coffeeStats.monthSales.filter(s => s.machineId === activeMachine.id);
  const monthExpenses = coffeeStats.monthExpenses.filter(x => x.machineId === activeMachine.id);
  const revenue = monthSales.reduce((a, s) => a + (Number(s.amount) || 0), 0);
  const expenses = monthExpenses.reduce((a, x) => a + (Number(x.amount) || 0), 0);
  const net = revenue - expenses;

  // Cumulative chart series (revenue per day, expenses per day, net cumulative)
  const today = new Date();
  const daysInMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0).getDate();
  const series = buildCoffeeSeries(monthSales, monthExpenses, daysInMonth);

  // Recent transactions (mixed) — last 30 days, newest first
  const recent = React.useMemo(() => {
    const items = [
      ...monthSales.map(s => ({
        kind: 'sale', id: s.id, date: s.date,
        title: s.note || 'Изтеглени',
        sub: '',
        amount: Number(s.amount) || 0,
        positive: true,
      })),
      ...monthExpenses.map(x => ({
        kind: 'expense', id: x.id, date: x.date,
        title: KIND_LABEL[x.kind] || 'Разход',
        sub: x.note || '',
        amount: -x.amount,
        positive: false,
        expenseKind: x.kind,
      })),
    ];
    items.sort((a, b) => b.date.localeCompare(a.date));
    return items.slice(0, 30);
  }, [monthSales, monthExpenses]);

  return (
    <div className="page-in" style={{ paddingBottom: 200 }}>
      <ScreenHeader
        eyebrow="Coffee · separate ledger"
        title="Coffee machines"
        right={
          <button onClick={onManageMachines} style={{
            padding: '7px 12px', borderRadius: 14,
            background: tokens.inset, border: `1px solid ${tokens.hairline}`,
            color: tokens.ink2, fontFamily: tokens.sans, fontSize: 12, fontWeight: 500,
            letterSpacing: 0.2, cursor: 'pointer',
          }}>Manage</button>
        }
      />

      {/* Machine switcher (chips) */}
      {machines.length > 1 && (
        <div style={{
          display: 'flex', gap: 8, padding: '0 18px 6px',
          overflowX: 'auto', scrollbarWidth: 'none',
        }}>
          {machines.map(m => {
            const active = m.id === activeMachine.id;
            return (
              <button key={m.id} onClick={() => store.setActiveMachine(m.id)}
                style={{
                  flex: '0 0 auto',
                  padding: '7px 14px', borderRadius: 16,
                  background: active ? tokens.ink : tokens.card,
                  border: `1px solid ${active ? tokens.ink : tokens.hairline}`,
                  color: active ? tokens.paper : tokens.ink2,
                  fontFamily: tokens.sans, fontSize: 12, fontWeight: 500,
                  letterSpacing: 0.2, cursor: 'pointer',
                  transition: 'background 200ms, color 200ms, border-color 200ms',
                }}>{m.name}</button>
            );
          })}
        </div>
      )}

      {/* Hero: net profit */}
      <div style={{ padding: '8px 22px 0' }}>
        <div style={{
          fontFamily: tokens.sans, fontSize: 11, fontWeight: 500, letterSpacing: 0.6,
          textTransform: 'uppercase', color: tokens.ink3, marginBottom: 6,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <span>Net this month</span>
          <span style={{ color: tokens.ink4, fontWeight: 400, letterSpacing: 0.4 }}>· {activeMachine.name}</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
          <div style={{
            fontFamily: tokens.serif, fontSize: 56, lineHeight: 1,
            color: net >= 0 ? tokens.ink : tokens.bad,
            fontVariantNumeric: 'tabular-nums', letterSpacing: -1.6,
          }}>
            <CountNumber value={net} format={(v) => fmtEUR(v, { sym: false, decimals: 0 })}/>
          </div>
          <span style={{ fontSize: 32, color: tokens.ink3, fontFamily: tokens.serif, fontStyle: 'italic' }}>€</span>
        </div>

        <div style={{
          marginTop: 10, display: 'flex', gap: 14,
          fontFamily: tokens.sans, fontSize: 12, color: tokens.ink3,
        }}>
          <span><span style={{ color: tokens.sageDeep, fontWeight: 600 }}>+{fmtEUR(revenue, { decimals: 0 })}</span> revenue</span>
          <span><span style={{ color: tokens.bad, fontWeight: 600 }}>−{fmtEUR(expenses, { decimals: 0 })}</span> expenses</span>
        </div>
      </div>

      {/* Cumulative chart */}
      <div style={{ padding: '16px 18px 0' }}>
        <CoffeeChart series={series} daysInMonth={daysInMonth}/>
      </div>

      {/* Action buttons */}
      <div style={{ padding: '14px 18px 0' }}>
        <div style={{ display: 'flex', gap: 10 }}>
          <button onClick={onAddSale} style={{
            flex: 1, padding: '14px 12px', borderRadius: 16,
            background: tokens.sageSoft, border: 'none', cursor: 'pointer',
            color: tokens.sageDeep, fontFamily: tokens.sans, fontSize: 14, fontWeight: 600,
            letterSpacing: 0.2,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}
            onPointerDown={(e) => e.currentTarget.style.transform = 'scale(0.97)'}
            onPointerUp={(e) => e.currentTarget.style.transform = 'scale(1)'}
            onPointerLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
          >
            <span style={{ fontSize: 16 }}>+</span>
            <span>Income</span>
          </button>
          <button onClick={onAddExpense} style={{
            flex: 1, padding: '14px 12px', borderRadius: 16,
            background: tokens.inset, border: `1px solid ${tokens.hairline}`, cursor: 'pointer',
            color: tokens.ink2, fontFamily: tokens.sans, fontSize: 14, fontWeight: 600,
            letterSpacing: 0.2,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}
            onPointerDown={(e) => e.currentTarget.style.transform = 'scale(0.97)'}
            onPointerUp={(e) => e.currentTarget.style.transform = 'scale(1)'}
            onPointerLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
          >
            <span style={{ fontSize: 16 }}>−</span>
            <span>Expense</span>
          </button>
        </div>
      </div>

      {/* Stats card */}
      <div style={{ padding: '16px 18px 0' }}>
        <Card padding={0}>
          <div style={{ padding: '14px' }}>
            <SectionHeader>Month at a glance</SectionHeader>
            <StatRow label="Income" value={fmtEUR(revenue, { decimals: 0 })}/>
            <StatRow label="Expenses" value={fmtEUR(expenses, { decimals: 0 })}/>
            <StatRow label="Margin" value={`${revenue > 0 ? Math.round((net / revenue) * 100) : 0}%`} isLast/>
          </div>
        </Card>
      </div>

      {/* Transactions */}
      <div style={{ padding: '16px 18px 0' }}>
        <SectionHeader trailing={`${recent.length} entries`}>Recent</SectionHeader>
        <Card padding={0}>
          {recent.length === 0 && (
            <div style={{ padding: 22, textAlign: 'center', fontFamily: tokens.sans, fontSize: 13, color: tokens.ink3 }}>
              No activity yet this month.
            </div>
          )}
          {recent.map((t, i) => (
            <CoffeeRow key={t.id} t={t} isLast={i === recent.length - 1} delay={i * 30}/>
          ))}
        </Card>
      </div>
    </div>
  );
}

// ── Section header (mirror of Stats) ─────────────────────────────────────
function SectionHeader({ children, trailing }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      padding: '0 4px 10px',
    }}>
      <span style={{
        fontFamily: tokens.sans, fontSize: 11, fontWeight: 500, letterSpacing: 0.6,
        textTransform: 'uppercase', color: tokens.ink3,
      }}>{children}</span>
      {trailing && (
        <span style={{
          fontFamily: tokens.sans, fontSize: 11, color: tokens.ink3,
          fontVariantNumeric: 'tabular-nums',
        }}>{trailing}</span>
      )}
    </div>
  );
}

// ── Stat row inside the glance card ──────────────────────────────────────
function StatRow({ label, value, isLast }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      padding: '10px 0',
      borderBottom: isLast ? 'none' : `1px solid ${tokens.hairline}`,
    }}>
      <span style={{
        fontFamily: tokens.sans, fontSize: 11, color: tokens.ink3,
        textTransform: 'uppercase', letterSpacing: 0.4, fontWeight: 500,
      }}>{label}</span>
      <span style={{
        fontFamily: tokens.serif, fontSize: 18, color: tokens.ink,
        fontVariantNumeric: 'tabular-nums', letterSpacing: -0.3,
      }}>{value}</span>
    </div>
  );
}

// ── Coffee transaction row ───────────────────────────────────────────────
function CoffeeRow({ t, isLast, delay = 0 }) {
  const d = new Date(t.date);
  const dayLabel = `${d.getDate()} ${MONTHS_SHORT[d.getMonth()]}`;
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 14px',
      borderBottom: isLast ? 'none' : `1px solid ${tokens.hairline}`,
      animation: 'list-row-in 320ms cubic-bezier(0.22,1,0.36,1) both',
      animationDelay: `${delay}ms`,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 16,
        background: t.positive ? tokens.sageSoft : `${tokens.bad}18`,
        color: t.positive ? tokens.sageDeep : tokens.bad,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 14, fontFamily: tokens.sans, fontWeight: 500,
      }}>
        {t.positive ? '€' : (KIND_ICON[t.expenseKind] || '·')}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: tokens.sans, fontSize: 14, color: tokens.ink, fontWeight: 500,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{t.title}</div>
        <div style={{
          fontFamily: tokens.sans, fontSize: 11, color: tokens.ink3, marginTop: 2,
        }}>{dayLabel}{t.sub ? ` · ${t.sub}` : ''}</div>
      </div>
      <div style={{
        fontFamily: tokens.serif, fontSize: 16,
        color: t.positive ? tokens.ink : tokens.bad,
        fontVariantNumeric: 'tabular-nums', letterSpacing: -0.2, whiteSpace: 'nowrap',
      }}>
        {t.positive ? '+' : '−'}{fmtEUR(Math.abs(t.amount), { decimals: 2 })}
      </div>
    </div>
  );
}

// ── Empty state ──────────────────────────────────────────────────────────
function CoffeeEmpty({ onAdd }) {
  return (
    <div className="page-in" style={{
      padding: '60px 32px 110px', textAlign: 'center',
    }}>
      <div style={{
        margin: '0 auto 22px', width: 88, height: 88, borderRadius: 44,
        background: tokens.sageSoft, color: tokens.sageDeep,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 40,
        animation: 'breathe 3s ease-in-out infinite',
      }}>☕</div>
      <h2 style={{
        margin: '0 0 8px', fontFamily: tokens.serif, fontWeight: 400,
        fontSize: 28, color: tokens.ink, letterSpacing: -0.5,
      }}>No machines yet</h2>
      <p style={{
        margin: '0 0 24px', fontFamily: tokens.sans, fontSize: 14,
        color: tokens.ink3, lineHeight: 1.5,
      }}>Add your coffee machine to start tracking sales and expenses separately from the rest of your money.</p>
      <button onClick={onAdd} style={{
        padding: '12px 22px', borderRadius: 18,
        background: tokens.ink, color: tokens.paper, border: 'none',
        fontFamily: tokens.sans, fontSize: 14, fontWeight: 500, letterSpacing: 0.2,
        cursor: 'pointer',
      }}>+ Add machine</button>
    </div>
  );
}

// ── Series builder ───────────────────────────────────────────────────────
// Returns { revenuePerDay[], expensePerDay[], cumulativeNet[] } indexed 0..daysInMonth
function buildCoffeeSeries(sales, expenses, daysInMonth) {
  const rev = new Array(daysInMonth + 1).fill(0);
  const exp = new Array(daysInMonth + 1).fill(0);
  sales.forEach(s => {
    const d = new Date(s.date).getDate();
    rev[Math.min(daysInMonth, Math.max(1, d))] += Number(s.amount) || 0;
  });
  expenses.forEach(x => {
    const d = new Date(x.date).getDate();
    exp[Math.min(daysInMonth, Math.max(1, d))] += Number(x.amount) || 0;
  });
  const cum = new Array(daysInMonth + 1).fill(0);
  let running = 0;
  for (let i = 0; i <= daysInMonth; i++) {
    running += rev[i] - exp[i];
    cum[i] = running;
  }
  return { rev, exp, cum };
}

// ── Coffee chart ─────────────────────────────────────────────────────────
function CoffeeChart({ series, daysInMonth }) {
  const W = 320, H = 180;
  const padL = 8, padR = 8, padT = 14, padB = 26;

  // y-domain: encompass min/max of cumulative net (could go negative early in month)
  const cum = series.cum;
  const minVal = Math.min(0, ...cum);
  const maxVal = Math.max(1, ...cum);
  const range = Math.max(1, maxVal - minVal);

  const x = (day) => padL + (day / daysInMonth) * (W - padL - padR);
  const y = (val) => padT + (1 - (val - minVal) / range) * (H - padT - padB);
  const yZero = y(0);

  let pathD = `M ${x(0).toFixed(2)} ${y(cum[0]).toFixed(2)}`;
  for (let i = 1; i <= daysInMonth; i++) {
    pathD += ` L ${x(i).toFixed(2)} ${y(cum[i]).toFixed(2)}`;
  }
  let areaD = `M ${x(0).toFixed(2)} ${yZero.toFixed(2)}`;
  for (let i = 0; i <= daysInMonth; i++) {
    areaD += ` L ${x(i).toFixed(2)} ${y(cum[i]).toFixed(2)}`;
  }
  areaD += ` L ${x(daysInMonth).toFixed(2)} ${yZero.toFixed(2)} Z`;

  const ticks = [1, 7, 14, 21, 28];
  if (daysInMonth > 28 && !ticks.includes(daysInMonth)) ticks.push(daysInMonth);

  // Path draw-on animation
  const pathRef = React.useRef(null);
  const [pathLen, setPathLen] = React.useState(0);
  React.useEffect(() => {
    if (pathRef.current) {
      try { setPathLen(pathRef.current.getTotalLength()); } catch (e) {}
    }
  }, [pathD]);

  return (
    <Card padding={0}>
      <div style={{ padding: '14px 12px 8px' }}>
        <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: 'block', overflow: 'visible' }}>
          <defs>
            <linearGradient id="coffee-area" x1="0" x2="0" y1="0" y2="1">
              <stop offset="0%" stopColor={tokens.sage} stopOpacity="0.22"/>
              <stop offset="100%" stopColor={tokens.sage} stopOpacity="0"/>
            </linearGradient>
          </defs>

          {/* Zero line */}
          <line x1={padL} x2={W - padR} y1={yZero} y2={yZero}
            stroke={tokens.hairline} strokeDasharray="2 4"/>

          {/* Area */}
          <path d={areaD} fill="url(#coffee-area)" style={{
            animation: 'fade-in 720ms cubic-bezier(0.22,1,0.36,1) both 240ms',
          }}/>

          {/* Main line */}
          <path
            ref={pathRef}
            d={pathD}
            fill="none"
            stroke={tokens.ink}
            strokeWidth="2.4"
            strokeLinecap="round"
            strokeLinejoin="round"
            style={pathLen > 0 ? {
              strokeDasharray: pathLen,
              strokeDashoffset: pathLen,
              animation: 'stats-line-draw 980ms cubic-bezier(0.22,1,0.36,1) forwards',
            } : undefined}
          />

          {/* End-point dot */}
          <circle
            cx={x(daysInMonth)}
            cy={y(cum[daysInMonth])}
            r="4"
            fill={tokens.ink}
            style={{
              animation: 'stats-dot-pop 320ms cubic-bezier(0.34,1.4,0.64,1) both 1000ms',
              transformOrigin: `${x(daysInMonth)}px ${y(cum[daysInMonth])}px`,
            }}
          />

          {/* X-axis ticks */}
          {ticks.map(t => (
            <text key={t} x={x(t)} y={H - 8}
              fontFamily={tokens.sans} fontSize="9" fill={tokens.ink3} textAnchor="middle">{t}</text>
          ))}
        </svg>

        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          padding: '0 4px',
        }}>
          <span style={{ fontFamily: tokens.sans, fontSize: 11, color: tokens.ink3, letterSpacing: 0.4 }}>
            CUMULATIVE NET
          </span>
          <span style={{
            fontFamily: tokens.serif, fontSize: 16, color: tokens.ink,
            fontVariantNumeric: 'tabular-nums', letterSpacing: -0.2,
          }}>
            {fmtEUR(cum[daysInMonth] || 0, { decimals: 0 })}
          </span>
        </div>
      </div>
    </Card>
  );
}

// ── Add coffee income sheet ──────────────────────────────────────────────
function AddCoffeeSaleSheet({ open, onClose, onSave, machineName }) {
  const [amount, setAmount] = React.useState('');
  const [note, setNote] = React.useState('');
  const [date, setDate] = React.useState(() => isoToday());

  React.useEffect(() => {
    if (open) {
      setAmount('');
      setNote('');
      setDate(isoToday());
    }
  }, [open]);

  // Quick-fill suggestions for the note (mid-month / month-end)
  const today = new Date();
  const suggestNote = today.getDate() <= 20 ? '15-то' : '30-то';

  return (
    <Sheet open={open} onClose={onClose} title="Log income">
      <div style={{ padding: '4px 4px 8px' }}>
        <div style={{
          fontFamily: tokens.sans, fontSize: 12, color: tokens.ink3,
          marginBottom: 16, letterSpacing: 0.2,
        }}>For {machineName}</div>

        <Field label="Amount">
          <CurrencyInput value={amount} onChange={setAmount} placeholder="0,00"/>
        </Field>

        <Field label="Note (optional)">
          <input type="text" value={note} onChange={(e) => setNote(e.target.value)}
            placeholder={suggestNote}
            style={inputStyle()}/>
        </Field>

        <Field label="Date">
          <input type="date" value={date} onChange={(e) => setDate(e.target.value)}
            style={inputStyle()}/>
        </Field>

        <SheetActions
          onCancel={onClose}
          onSave={() => onSave({ amount: Number(amount), note: note.trim() || suggestNote, date })}
          disabled={!amount || Number(amount) <= 0}
          saveLabel="Log income"
        />
      </div>
    </Sheet>
  );
}

// ── Add coffee expense sheet ─────────────────────────────────────────────
function AddCoffeeExpenseSheet({ open, onClose, onSave, machineName }) {
  const [kind, setKind] = React.useState('beans');
  const [amount, setAmount] = React.useState('');
  const [note, setNote] = React.useState('');
  const [date, setDate] = React.useState(() => isoToday());

  React.useEffect(() => {
    if (open) { setKind('beans'); setAmount(''); setNote(''); setDate(isoToday()); }
  }, [open]);

  return (
    <Sheet open={open} onClose={onClose} title="Add expense">
      <div style={{ padding: '4px 4px 8px' }}>
        <div style={{
          fontFamily: tokens.sans, fontSize: 12, color: tokens.ink3,
          marginBottom: 14, letterSpacing: 0.2,
        }}>For {machineName}</div>

        <Field label="Type">
          <div style={{
            display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6,
          }}>
            {COFFEE_KINDS.map(k => {
              const active = k.id === kind;
              return (
                <button key={k.id} onClick={() => setKind(k.id)} style={{
                  padding: '10px 4px', borderRadius: 12,
                  background: active ? tokens.ink : tokens.inset,
                  color: active ? tokens.paper : tokens.ink2,
                  border: `1px solid ${active ? tokens.ink : tokens.hairline}`,
                  fontFamily: tokens.sans, fontSize: 11, fontWeight: 500,
                  cursor: 'pointer', display: 'flex', flexDirection: 'column',
                  alignItems: 'center', gap: 4,
                  transition: 'all 160ms',
                }}>
                  <span style={{ fontSize: 18 }}>{k.icon}</span>
                  <span>{k.label}</span>
                </button>
              );
            })}
          </div>
        </Field>

        <Field label="Amount">
          <CurrencyInput value={amount} onChange={setAmount} placeholder="0,00"/>
        </Field>

        <Field label="Note (optional)">
          <input type="text" value={note} onChange={(e) => setNote(e.target.value)}
            placeholder="e.g. 2кг specialty"
            style={inputStyle()}/>
        </Field>

        <Field label="Date">
          <input type="date" value={date} onChange={(e) => setDate(e.target.value)}
            style={inputStyle()}/>
        </Field>

        <SheetActions
          onCancel={onClose}
          onSave={() => onSave({ kind, amount: Number(amount), note, date })}
          disabled={!amount || Number(amount) <= 0}
          saveLabel="Save expense"
        />
      </div>
    </Sheet>
  );
}

// ── Manage machines screen ───────────────────────────────────────────────
function ManageMachinesScreen({ store, onBack, onOpenAddMachine }) {
  const machines = store.coffee.machines;
  return (
    <div className="page-in" style={{ paddingBottom: 110 }}>
      <ScreenHeader
        eyebrow={<button onClick={onBack} style={backLinkStyle()}>← Coffee</button>}
        title="Machines"
        right={
          <button onClick={onOpenAddMachine} style={{
            padding: '7px 14px', borderRadius: 14,
            background: tokens.ink, border: 'none',
            color: tokens.paper, fontFamily: tokens.sans, fontSize: 12, fontWeight: 500,
            cursor: 'pointer',
          }}>+ Add</button>
        }
      />
      <div style={{ padding: '4px 18px 0' }}>
        {machines.length === 0 && (
          <Card>
            <div style={{ textAlign: 'center', padding: 14 }}>
              <div style={{ fontFamily: tokens.serif, fontSize: 18, color: tokens.ink2, marginBottom: 4, fontStyle: 'italic' }}>
                No machines
              </div>
              <div style={{ fontFamily: tokens.sans, fontSize: 13, color: tokens.ink3 }}>
                Tap + Add to create one.
              </div>
            </div>
          </Card>
        )}
        {machines.length > 0 && (
          <Card padding={0}>
            {machines.map((m, i) => (
              <div key={m.id} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '14px',
                borderBottom: i < machines.length - 1 ? `1px solid ${tokens.hairline}` : 'none',
              }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 18,
                  background: tokens.sageSoft, color: tokens.sageDeep,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 18,
                }}>☕</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    fontFamily: tokens.sans, fontSize: 14, color: tokens.ink, fontWeight: 500,
                  }}>{m.name}</div>
                  <div style={{
                    fontFamily: tokens.sans, fontSize: 11, color: tokens.ink3, marginTop: 2,
                  }}>
                    Bought {fmtEUR(m.purchasePrice || 0, { decimals: 0 })}
                    {m.purchaseDate ? ` · ${m.purchaseDate}` : ''}
                  </div>
                </div>
                <button onClick={() => {
                  if (confirm(`Delete "${m.name}" and all its data?`)) store.deleteMachine(m.id);
                }} style={{
                  padding: '6px 10px', borderRadius: 10,
                  background: 'transparent', border: `1px solid ${tokens.hairline}`,
                  color: tokens.bad, fontFamily: tokens.sans, fontSize: 11,
                  cursor: 'pointer',
                }}>Delete</button>
              </div>
            ))}
          </Card>
        )}
      </div>
    </div>
  );
}

// ── Add machine sheet ────────────────────────────────────────────────────
function AddMachineSheet({ open, onClose, onSave }) {
  const [name, setName] = React.useState('');
  const [price, setPrice] = React.useState('');
  const [date, setDate] = React.useState(() => isoToday());

  React.useEffect(() => {
    if (open) { setName(''); setPrice(''); setDate(isoToday()); }
  }, [open]);

  return (
    <Sheet open={open} onClose={onClose} title="Add machine">
      <div style={{ padding: '4px 4px 8px' }}>
        <Field label="Name">
          <input type="text" value={name} onChange={(e) => setName(e.target.value)}
            placeholder="e.g. Офис — lobby"
            style={inputStyle()}/>
        </Field>
        <Field label="Purchase price (for break-even)">
          <CurrencyInput value={price} onChange={setPrice} placeholder="0"/>
        </Field>
        <Field label="Purchase date">
          <input type="date" value={date} onChange={(e) => setDate(e.target.value)}
            style={inputStyle()}/>
        </Field>

        <SheetActions
          onCancel={onClose}
          onSave={() => onSave({ name: name.trim() || 'Coffee machine', purchasePrice: Number(price) || 0, purchaseDate: date })}
          disabled={!name.trim()}
          saveLabel="Add machine"
        />
      </div>
    </Sheet>
  );
}

// ── Reusable form bits (mirror existing style) ───────────────────────────
function Field({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{
        fontFamily: tokens.sans, fontSize: 11, fontWeight: 500, letterSpacing: 0.5,
        textTransform: 'uppercase', color: tokens.ink3, marginBottom: 7,
      }}>{label}</div>
      {children}
    </div>
  );
}

function inputStyle() {
  return {
    width: '100%', padding: '12px 14px', borderRadius: 12,
    background: tokens.inset, border: `1px solid ${tokens.hairline}`,
    color: tokens.ink, fontFamily: tokens.sans, fontSize: 15,
    outline: 'none', boxSizing: 'border-box',
  };
}
function backLinkStyle() {
  return {
    background: 'transparent', border: 'none',
    color: tokens.ink3, fontFamily: tokens.sans, fontSize: 12,
    fontWeight: 500, letterSpacing: 0.4, textTransform: 'uppercase',
    padding: 0, cursor: 'pointer',
  };
}

function CurrencyInput({ value, onChange, placeholder = '0' }) {
  return (
    <div style={{ position: 'relative' }}>
      <input
        type="text" inputMode="decimal"
        value={value} onChange={(e) => onChange(e.target.value.replace(',', '.'))}
        placeholder={placeholder}
        style={{ ...inputStyle(), paddingRight: 32 }}/>
      <span style={{
        position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)',
        fontFamily: tokens.serif, fontSize: 16, color: tokens.ink3, pointerEvents: 'none',
      }}>€</span>
    </div>
  );
}

function Stepper({ value, onChange, min = 0, max = 999 }) {
  const dec = () => onChange(Math.max(min, Number(value) - 1));
  const inc = () => onChange(Math.min(max, Number(value) + 1));
  const btnStyle = {
    width: 44, height: 44, borderRadius: 12,
    background: tokens.inset, border: `1px solid ${tokens.hairline}`,
    color: tokens.ink, fontFamily: tokens.sans, fontSize: 20, fontWeight: 400,
    cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
  };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <button onClick={dec} style={btnStyle}>−</button>
      <input
        type="number" value={value} onChange={(e) => onChange(Math.max(min, Math.min(max, Number(e.target.value) || min)))}
        style={{
          ...inputStyle(),
          flex: 1, textAlign: 'center',
          fontFamily: tokens.serif, fontSize: 22, fontWeight: 400,
          letterSpacing: -0.3,
        }}/>
      <button onClick={inc} style={btnStyle}>+</button>
    </div>
  );
}

function SheetActions({ onCancel, onSave, disabled, saveLabel = 'Save' }) {
  return (
    <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
      <button onClick={onCancel} style={{
        flex: 1, padding: '13px', borderRadius: 14,
        background: tokens.inset, border: 'none',
        color: tokens.ink2, fontFamily: tokens.sans, fontSize: 14, fontWeight: 500,
        cursor: 'pointer',
      }}>Cancel</button>
      <button onClick={onSave} disabled={disabled} style={{
        flex: 2, padding: '13px', borderRadius: 14,
        background: disabled ? tokens.inset : tokens.ink,
        color: disabled ? tokens.ink4 : tokens.paper,
        border: 'none',
        fontFamily: tokens.sans, fontSize: 14, fontWeight: 500,
        cursor: disabled ? 'default' : 'pointer',
      }}>{saveLabel}</button>
    </div>
  );
}

function isoToday() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}

Object.assign(window, {
  CoffeeScreen, ManageMachinesScreen,
  AddCoffeeSaleSheet, AddCoffeeExpenseSheet, AddMachineSheet,
  COFFEE_KINDS, KIND_LABEL, KIND_ICON,
});
