// ─────────────────────────────────────────────────────────────────────
// UPLOAD RECEIPT — steps 2-3 + the flow controller.
//   ReviewStep  · what the archive read (totals locked to the document)
//   AllocateStep· per-line ledger → car (make/model/VIN) / many / overhead
//   AllocatorSheet · the per-line target picker
//   DoneStep    · records written + reimbursement roll-up
//   ReceiptFlow · state machine wiring it together
// ─────────────────────────────────────────────────────────────────────

const { useState: useRcA } = React;

// member + vehicle helpers ------------------------------------------------
const memberById = (id) => RECEIPT.members.find(m => m.id === id) || RECEIPT.paidBy;
const ownerOf = (vid) => memberById(RECEIPT.vehicleOwner[vid]);
const ledgerName = (v) => (v && v.status === 'In Restoration' ? 'Restoration ledger' : 'Service ledger');

// ── editable, "correct a misread" header field ──────────────────────────
function EditableField({ label, value, onChange, mono, conf = 'High' }) {
  const [editing, setEditing] = useRcA(false);
  return (
    <div style={{ background: P.ink, padding: '11px 12px', minWidth: 0 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
        <RcMono size={8} color={P.mute} tracking="0.16em">{label}</RcMono>
        <button onClick={() => setEditing(e => !e)} aria-label={`Edit ${label}`} style={{
          background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, lineHeight: 0,
          color: editing ? P.gold : P.slate,
        }}>
          <Icon name={editing ? 'Check' : 'Pencil'} size={12} color={editing ? P.gold : P.slate} strokeWidth={2} />
        </button>
      </div>
      {editing ? (
        <input autoFocus value={value} onChange={(e) => onChange(e.target.value)}
          onBlur={() => setEditing(false)} onKeyDown={(e) => { if (e.key === 'Enter') setEditing(false); }}
          style={{
            width: '100%', marginTop: 4, background: 'transparent', border: 'none',
            borderBottom: `1px solid ${P.gold}`, outline: 'none', color: P.paper,
            fontFamily: mono ? T.mono : T.body, fontSize: 12.5, padding: '2px 0',
          }} />
      ) : (
        <div onClick={() => setEditing(true)} style={{
          fontFamily: mono ? T.mono : T.body, fontSize: 12.5, color: P.paper, marginTop: 4, cursor: 'text',
        }}>{value}</div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// STEP 2 — REVIEW
// ─────────────────────────────────────────────────────────────────────
function ReviewStep({ header, setHeader, onContinue }) {
  const { currency } = RECEIPT;
  const tot = receiptTotals();
  return (
    <div className="proto-scroll" style={{ flex: 1, overflow: 'auto', background: P.ink }} data-screen-label="rc-review">
      <div style={{ padding: '18px 22px 12px' }}>
        <RcMono size={9} color={P.gold} style={{ display: 'block' }}>EXTRACTED · {RECEIPT.lines.length} LINE ITEMS</RcMono>
        <div style={{ fontFamily: T.display, fontWeight: 700, fontSize: 32, lineHeight: 0.92, letterSpacing: '-0.02em', color: P.paper, marginTop: 8 }}>
          REVIEW THE<br />EXTRACTION
        </div>
      </div>

      {/* original preserved */}
      <div style={{ padding: '6px 22px 16px' }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'stretch', background: P.graphite, padding: 12, borderLeft: `2px solid ${P.gold}` }}>
          <div style={{ width: 52, height: 66, flexShrink: 0, overflow: 'hidden', border: `1px solid ${P.slate}` }}>
            <div style={{ transform: 'scale(0.38)', transformOrigin: 'top left', width: 294 }}>
              <ReceiptDocument compact />
            </div>
          </div>
          <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <div style={{ fontFamily: T.body, fontSize: 12.5, color: P.paper, fontWeight: 500 }}>{RECEIPT.intake.file}</div>
            <RcMono size={8} color={P.gold} style={{ marginTop: 5, display: 'inline-flex', alignItems: 'center', gap: 5 }}>
              <Icon name="archive" size={11} color={P.gold} strokeWidth={1.8} /> ORIGINAL PRESERVED · VAULT
            </RcMono>
          </div>
        </div>
      </div>

      {/* header fields */}
      <RowRule>VENDOR &amp; DOCUMENT</RowRule>
      <div style={{ padding: '12px 22px 8px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1, background: P.slate, border: `1px solid ${P.slate}` }}>
          <div style={{ gridColumn: '1 / -1' }}>
            <EditableField label="Vendor" value={header.vendor} onChange={(v) => setHeader(h => ({ ...h, vendor: v }))} />
          </div>
          <EditableField label="Date" value={header.date} onChange={(v) => setHeader(h => ({ ...h, date: v }))} mono />
          <div style={{ background: P.ink, padding: '11px 12px' }}>
            <RcMono size={8} color={P.mute} tracking="0.16em">Vendor type</RcMono>
            <div style={{ fontFamily: T.body, fontSize: 12.5, color: P.paper, marginTop: 4 }}>{RECEIPT.vendor.kind}</div>
          </div>
          <div style={{ background: P.ink, padding: '11px 12px' }}>
            <RcMono size={8} color={P.mute} tracking="0.16em">Invoice no.</RcMono>
            <div style={{ fontFamily: T.mono, fontSize: 12, color: P.paper, marginTop: 4 }}>{RECEIPT.vendor.invoiceNo}</div>
          </div>
          <div style={{ background: P.ink, padding: '11px 12px' }}>
            <RcMono size={8} color={P.mute} tracking="0.16em">VAT-ID</RcMono>
            <div style={{ fontFamily: T.mono, fontSize: 11, color: P.paper, marginTop: 4 }}>{RECEIPT.vendor.vatId}</div>
          </div>
        </div>
        <RcMono size={8.5} color={P.mute} style={{ display: 'block', marginTop: 9, lineHeight: 1.5 }}>
          Tap any field to correct a misread.
        </RcMono>
      </div>

      {/* currency */}
      <RowRule>CURRENCY</RowRule>
      <div style={{ padding: '12px 22px 8px' }}>
        <div style={{ background: P.graphite, padding: 14, display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <span style={{ fontFamily: T.display, fontSize: 30, fontWeight: 700, color: P.gold, lineHeight: 1 }}>{currency.symbol}</span>
            <div>
              <div style={{ fontFamily: T.display, fontSize: 16, fontWeight: 700, color: P.paper, lineHeight: 1 }}>{currency.code}</div>
              <RcMono size={8} color={P.mute} style={{ marginTop: 3, display: 'block' }}>ORIGINAL</RcMono>
            </div>
          </div>
          <div style={{ flex: 1, height: 28, borderLeft: `1px solid ${P.slate}`, paddingLeft: 14, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <div style={{ fontFamily: T.body, fontSize: 11.5, color: P.bone }}>
              Home ledger <span style={{ color: P.paper, fontWeight: 600 }}>{currency.home}</span>
            </div>
            <RcMono size={8} color={P.mute} style={{ marginTop: 3, display: 'block' }}>
              {currency.symbol}1 = {currency.homeSymbol}{currency.rate} · {currency.rateDate} · {currency.rateSource}
            </RcMono>
          </div>
        </div>
      </div>

      {/* line items */}
      <RowRule>LINE ITEMS</RowRule>
      <div style={{ padding: '10px 22px 8px', display: 'flex', flexDirection: 'column' }}>
        {RECEIPT.lines.map((l, i) => (
          <div key={l.id} style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 14,
            padding: '12px 0', borderBottom: i < RECEIPT.lines.length - 1 ? `1px solid ${P.graphite}` : 'none',
          }}>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ fontFamily: T.body, fontSize: 12.5, color: P.paper, lineHeight: 1.35 }}>{l.desc}</div>
              <RcMono size={8} color={P.mute} style={{ marginTop: 4, display: 'block' }}>{l.qty} {l.unit.toUpperCase()}</RcMono>
            </div>
            <div style={{ textAlign: 'right', flexShrink: 0 }}>
              <div style={{ fontFamily: T.mono, fontSize: 12.5, color: P.paper, fontWeight: 500 }}>{eur(l.net)}</div>
              <RcMono size={8} color={P.mute} style={{ marginTop: 3, display: 'block' }}>{usd(toHome(l.net))}</RcMono>
            </div>
          </div>
        ))}
      </div>

      {/* totals — locked */}
      <div style={{ padding: '10px 22px 8px' }}>
        <div style={{ background: P.graphite, padding: 16 }}>
          {[['Subtotal', tot.sub], [`VAT · ${Math.round(RECEIPT.vatRate * 100)}%`, tot.vat]].map(([k, v]) => (
            <div key={k} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 9 }}>
              <RcMono size={9} color={P.mute} tracking="0.12em">{k}</RcMono>
              <span style={{ fontFamily: T.mono, fontSize: 12, color: P.bone }}>{eur(v)}</span>
            </div>
          ))}
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 6, paddingTop: 12, borderTop: `1px solid ${P.slate}` }}>
            <div>
              <RcMono size={8.5} color={P.gold} tracking="0.16em">Total</RcMono>
              <RcMono size={8} color={P.mute} style={{ marginTop: 3, display: 'block' }}>{usd(tot.home)} HOME</RcMono>
            </div>
            <span style={{ fontFamily: T.display, fontSize: 26, fontWeight: 700, color: P.paper, letterSpacing: '-0.02em' }}>{eur(tot.total)}</span>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10 }}>
          <Icon name="Lock" size={12} color={P.gold} strokeWidth={1.8} />
          <RcMono size={8.5} color={P.mute} tracking="0.1em" style={{ lineHeight: 1.5 }}>
            Totals are read from the document — never keyed by hand.
          </RcMono>
        </div>
      </div>

      {/* CTA */}
      <div style={{ padding: '16px 22px 14px' }}>
        <button onClick={onContinue} style={{
          width: '100%', height: 52, background: P.gold, border: `1px solid ${P.gold}`, color: P.ink, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          fontFamily: T.mono, fontSize: 11, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase',
        }}>
          Allocate line items
          <Icon name="arrow" size={16} color={P.ink} strokeWidth={2} />
        </button>
      </div>
      <div style={{ height: 16 }} />
    </div>
  );
}

// ── target chip (shown on a ledger row) ─────────────────────────────────
function TargetChip({ alloc, vehiclesById }) {
  if (!alloc) {
    return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: T.mono, fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', color: P.bone }}>
      <span style={{ width: 6, height: 6, border: `1px solid ${P.bone}`, borderRadius: 999 }} /> Choose target
    </span>;
  }
  if (alloc.mode === 'split') {
    const n = (alloc.splits || []).length;
    return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: T.mono, fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', color: P.gold }}>
      <Icon name="Split" size={11} color={P.gold} strokeWidth={1.8} /> Split · {n} {n === 1 ? 'vehicle' : 'vehicles'}
    </span>;
  }
  if (alloc.mode === 'overhead') {
    return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: T.mono, fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', color: P.bone }}>
      <span style={{ width: 6, height: 6, background: P.gold, borderRadius: 999, flexShrink: 0 }} /> Collection Overhead
    </span>;
  }
  if (alloc.mode === 'none') {
    return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontFamily: T.mono, fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', color: P.paper, background: P.ink, padding: '6px 8px' }}>
      <span style={{ width: 6, height: 6, background: P.gold, borderRadius: 999, flexShrink: 0 }} /> No assignment
    </span>;
  }
  const v = vehiclesById[alloc.vehicleId];
  if (!v) return null;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
      <span style={{ width: 6, height: 6, background: P.gold, borderRadius: 999, flexShrink: 0 }} />
      <span style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: '0.06em', textTransform: 'uppercase', color: P.paper, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
        {v.year} {v.make} · {v.vin.slice(-4)}
      </span>
    </span>
  );
}

// ─────────────────────────────────────────────────────────────────────
// STEP 3 — ALLOCATE
// ─────────────────────────────────────────────────────────────────────
function AllocateStep({ vehicles, targets, onEditLine, onContinue }) {
  const vehiclesById = {};
  vehicles.forEach(v => { vehiclesById[v.id] = v; });
  const { byTarget, unallocated } = rollUp(targets);
  const tot = receiptTotals();
  const allocatedNet = RECEIPT.lines.reduce((s, l) => s + (targets[l.id] ? l.net : 0), 0);
  const pct = Math.round((allocatedNet / tot.sub) * 100);
  const complete = unallocated.length === 0;

  // ordered roll-up: vehicles first, then overhead, then review
  const targetIds = Object.keys(byTarget).sort((a, b) => (a === 'overhead' || a === 'review' ? 1 : 0) - (b === 'overhead' || b === 'review' ? 1 : 0));

  return (
    <div className="proto-scroll" style={{ flex: 1, overflow: 'auto', background: P.ink }} data-screen-label="rc-allocate">
      <div style={{ padding: '18px 22px 10px' }}>
        <RcMono size={9} color={P.gold} style={{ display: 'block' }}>STEP 3 · COST ALLOCATION</RcMono>
        <div style={{ fontFamily: T.display, fontWeight: 700, fontSize: 32, lineHeight: 0.92, letterSpacing: '-0.02em', color: P.paper, marginTop: 8 }}>
          ALLOCATE<br />THE COST
        </div>
        <div style={{ fontFamily: T.body, fontSize: 12, color: P.mute, marginTop: 10, lineHeight: 1.5, maxWidth: 320 }}>
          Send each line to a specific car, several cars, or shared overhead.
          The archive pre-assigned what it was confident about — confirm or change.
        </div>
      </div>

      {/* progress */}
      <div style={{ padding: '4px 22px 14px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 7 }}>
          <RcMono size={8.5} color={P.mute} tracking="0.1em" style={{ whiteSpace: 'nowrap' }}>{RECEIPT.lines.length - unallocated.length} of {RECEIPT.lines.length} lines allocated</RcMono>
          <RcMono size={8.5} color={complete ? P.gold : P.bone}>{pct}%</RcMono>
        </div>
        <div style={{ height: 4, background: P.graphite }}>
          <div style={{ height: '100%', width: `${pct}%`, background: complete ? P.gold : P.bone, transition: 'width .25s' }} />
        </div>
      </div>

      {/* ledger */}
      <RowRule>THE LEDGER</RowRule>
      <div style={{ padding: '10px 22px 8px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {RECEIPT.lines.map(l => {
          const a = targets[l.id];
          return (
            <button key={l.id} onClick={() => onEditLine(l)} style={{
              width: '100%', textAlign: 'left', cursor: 'pointer',
              background: P.graphite, border: `1px solid ${a ? P.slate : P.signal}`,
              padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 9,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontFamily: T.body, fontSize: 12.5, color: P.paper, lineHeight: 1.3 }}>{l.desc}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
                    <span style={{ fontFamily: T.mono, fontSize: 11, color: P.bone, fontWeight: 500 }}>{eur(l.net)}</span>
                    <RcMono size={8} color={P.mute}>{usd(toHome(l.net))}</RcMono>
                  </div>
                </div>
                {a && a.ai && a.mode !== 'split' && <ConfTag level={l.conf} />}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10, paddingTop: 9, borderTop: `1px solid ${P.slate}` }}>
                <TargetChip alloc={a} vehiclesById={vehiclesById} />
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, flexShrink: 0 }}>
                  <RcMono size={8} color={P.gold}>{a ? 'Change' : 'Assign'}</RcMono>
                  <Icon name="arrow" size={13} color={P.gold} strokeWidth={1.6} />
                </span>
              </div>
            </button>
          );
        })}
      </div>

      {/* roll-up */}
      <div style={{ padding: '14px 22px 8px' }}>
        <RowRule>ALLOCATION SUMMARY</RowRule>
      </div>
      <div style={{ padding: '0 22px 8px', display: 'flex', flexDirection: 'column', gap: 1, background: P.slate, margin: '0 22px', border: `1px solid ${P.slate}` }}>
        {targetIds.map(id => {
          const t = byTarget[id];
          const isOver = id === 'overhead';
          const isReview = id === 'review';
          const v = vehiclesById[id];
          return (
            <div key={id} style={{ background: P.ink, padding: '12px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ width: 6, height: 6, borderRadius: 999, background: P.gold, border: 'none', flexShrink: 0 }} />
                  <div style={{ fontFamily: T.display, fontSize: 14, fontWeight: 600, color: P.paper, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {isReview ? 'No assignment' : isOver ? 'Collection Overhead' : `${v.year} ${v.make} ${v.model}`}
                  </div>
                </div>
                <RcMono size={8} color={P.mute} style={{ marginTop: 4, display: 'block', paddingLeft: 14 }}>
                  {isReview ? 'FLAGGED FOR REVIEW' : isOver ? 'SHARED EXPENSE' : `OWNER · ${ownerOf(id).name.toUpperCase()}`} · {t.lineIds.length} LINE{t.lineIds.length === 1 ? '' : 'S'}
                </RcMono>
              </div>
              <div style={{ textAlign: 'right', flexShrink: 0 }}>
                <div style={{ fontFamily: T.mono, fontSize: 12.5, color: P.paper, fontWeight: 500 }}>{eur(t.grossE)}</div>
                <RcMono size={8} color={P.mute} style={{ marginTop: 3, display: 'block' }}>{usd(t.homeUsd)}</RcMono>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ padding: '8px 22px 0' }}>
        <RcMono size={8} color={P.mute} style={{ lineHeight: 1.5, display: 'block' }}>Figures include VAT, distributed proportionally. Home values at {RECEIPT.currency.symbol}1 = {RECEIPT.currency.homeSymbol}{RECEIPT.currency.rate}.</RcMono>
      </div>

      {/* CTA */}
      <div style={{ padding: '18px 22px 14px' }}>
        <button onClick={onContinue} disabled={!complete} style={{
          width: '100%', height: 52,
          background: complete ? P.gold : P.graphite,
          border: `1px solid ${complete ? P.gold : P.slate}`,
          color: complete ? P.ink : P.mute, cursor: complete ? 'pointer' : 'not-allowed',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          fontFamily: T.mono, fontSize: 11, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase',
        }}>
          Add archive note
          <Icon name="arrow" size={16} color={complete ? P.ink : P.mute} strokeWidth={2} />
        </button>
        {!complete && <RcMono size={8.5} color={P.mute} style={{ display: 'block', textAlign: 'center', marginTop: 10 }}>{unallocated.length} line{unallocated.length === 1 ? '' : 's'} still need a target</RcMono>}
      </div>
      <div style={{ height: 14 }} />
    </div>
  );
}

Object.assign(window, { ReviewStep, AllocateStep, TargetChip, EditableField, memberById, ownerOf, ledgerName });
