// ─────────────────────────────────────────────────────────────────────
// UPLOAD RECEIPT — revised information architecture.
//
// The old flow asked "which vehicle is this receipt for?" BEFORE reading
// the document. That is wrong: a single invoice routinely carries line
// items for several different cars (owned by different people) plus shared
// shop overhead.
//
// The revised flow allocates AFTER extraction:
//   1 · CAPTURE   — bring the document in. Original is always preserved.
//   2 · REVIEW    — CV/OCR reads vendor, date, currency, line items,
//                   tax/VAT, totals. Totals stay locked to the document.
//   3 · ALLOCATE  — a per-line ledger. Each line → a specific car (with
//                   make / model / VIN), several cars, or shared overhead.
//   · RECORDS     — what got written where, plus a reimbursement roll-up.
//
// Principle, made literal: Actions create records. Records create the archive.
// ─────────────────────────────────────────────────────────────────────

const { useState: useRc, useMemo: useRcMemo } = React;

// ── small shared bits ───────────────────────────────────────────────────
function RcMono({ children, size = 9, color, tracking = '0.18em', style = {} }) {
  return (
    <span style={{
      fontFamily: T.mono, fontSize: size, letterSpacing: tracking,
      textTransform: 'uppercase', color: color || P.mute, ...style,
    }}>{children}</span>
  );
}

function Avatar({ initials, size = 26, filled = false }) {
  return (
    <span style={{
      width: size, height: size, flexShrink: 0,
      borderRadius: 999,
      background: filled ? P.gold : 'transparent',
      border: `1px solid ${P.gold}`,
      color: filled ? P.ink : P.gold,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: T.mono, fontSize: size <= 24 ? 7.5 : 8.5, fontWeight: 700,
      letterSpacing: '0.04em',
    }}>{initials}</span>
  );
}

function ConfTag({ level }) {
  const on = level === 'High';
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      fontFamily: T.mono, fontSize: 8, letterSpacing: '0.14em',
      textTransform: 'uppercase', color: on ? P.gold : P.mute,
    }}>
      <span style={{
        width: 5, height: 5, borderRadius: 999,
        background: on ? P.gold : 'transparent', border: `1px solid ${on ? P.gold : P.mute}`,
      }} />
      AI · {level}
    </span>
  );
}

// ── the faux "scan" of the original document (cream paper) ──────────────
function ReceiptDocument({ compact = false }) {
  const { vendor, currency } = RECEIPT;
  const tot = receiptTotals();
  return (
    <div style={{
      background: P.paper, color: P.ink,
      padding: compact ? 14 : '20px 20px 18px',
      fontFamily: T.body, position: 'relative', overflow: 'hidden',
    }}>
      {/* letterhead */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{
            fontFamily: T.display, fontWeight: 700, fontSize: compact ? 16 : 21,
            letterSpacing: '-0.01em', lineHeight: 1, color: P.ink,
          }}>{vendor.name}</div>
          <div style={{
            fontFamily: T.mono, fontSize: 8, letterSpacing: '0.16em', textTransform: 'uppercase',
            color: '#6b655a', marginTop: 6,
          }}>{vendor.kind} · {vendor.city}</div>
        </div>
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div style={{ fontFamily: T.mono, fontSize: 8, letterSpacing: '0.12em', color: '#6b655a' }}>INVOICE</div>
          <div style={{ fontFamily: T.mono, fontSize: 10, fontWeight: 600, color: P.ink, marginTop: 2 }}>{vendor.invoiceNo}</div>
          <div style={{ fontFamily: T.mono, fontSize: 8.5, color: '#6b655a', marginTop: 4 }}>{vendor.date}</div>
        </div>
      </div>

      <div style={{ height: 1, background: '#c9bfa8', margin: compact ? '12px 0 10px' : '16px 0 12px' }} />

      {/* column header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
        <span style={{ fontFamily: T.mono, fontSize: 7.5, letterSpacing: '0.18em', color: '#8a8170' }}>DESCRIPTION</span>
        <span style={{ fontFamily: T.mono, fontSize: 7.5, letterSpacing: '0.18em', color: '#8a8170' }}>NET · {currency.code}</span>
      </div>

      {/* line rows */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: compact ? 7 : 9 }}>
        {RECEIPT.lines.map(l => (
          <div key={l.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 14 }}>
            <span style={{ fontFamily: T.body, fontSize: compact ? 10 : 11.5, color: '#2a261f', lineHeight: 1.3 }}>{l.desc}</span>
            <span style={{ fontFamily: T.mono, fontSize: compact ? 10 : 11, color: P.ink, whiteSpace: 'nowrap', fontWeight: 500 }}>{eur(l.net)}</span>
          </div>
        ))}
      </div>

      <div style={{ height: 1, background: '#c9bfa8', margin: compact ? '12px 0 10px' : '14px 0 12px' }} />

      {/* totals */}
      {[
        ['Subtotal', eur(tot.sub)],
        [`VAT · ${Math.round(RECEIPT.vatRate * 100)}%`, eur(tot.vat)],
      ].map(([k, v]) => (
        <div key={k} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
          <span style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: '0.1em', color: '#6b655a', textTransform: 'uppercase' }}>{k}</span>
          <span style={{ fontFamily: T.mono, fontSize: 10.5, color: '#2a261f' }}>{v}</span>
        </div>
      ))}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        marginTop: 8, paddingTop: 8, borderTop: `2px solid ${P.ink}`,
      }}>
        <span style={{ fontFamily: T.display, fontSize: 13, fontWeight: 700, letterSpacing: '0.04em', color: P.ink }}>TOTAL DUE</span>
        <span style={{ fontFamily: T.display, fontSize: compact ? 17 : 20, fontWeight: 700, letterSpacing: '-0.01em', color: P.ink }}>{eur(tot.total)}</span>
      </div>

      {!compact && (
        <div style={{ marginTop: 12, fontFamily: T.mono, fontSize: 7.5, letterSpacing: '0.1em', color: '#8a8170', textTransform: 'uppercase' }}>
          VAT-ID {vendor.vatId} · {vendor.terms}
        </div>
      )}
    </div>
  );
}

// ── stepper header ──────────────────────────────────────────────────────
const RC_STEPS = [
  { id: 'capture',  label: 'Capture' },
  { id: 'review',   label: 'Review' },
  { id: 'allocate', label: 'Allocate' },
  { id: 'notes',    label: 'Notes' },
];

function ReceiptHeader({ stepId, onBack, done }) {
  const idx = RC_STEPS.findIndex(s => s.id === stepId);
  const shownIdx = done ? RC_STEPS.length : idx;
  return (
    <div style={{ flex: '0 0 auto', background: P.ink, borderBottom: `1px solid ${P.graphite}` }}>
      <div style={{ padding: '10px 18px 10px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onBack} aria-label="Back" style={{
          background: P.gold, border: 'none', borderRadius: 999,
          width: 34, height: 34, flexShrink: 0, color: P.ink, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
            strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round">
            <path d="M19 12H5M5 12l6-6M5 12l6 6" />
          </svg>
        </button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: T.display, fontWeight: 600, fontSize: 15, letterSpacing: '0.02em', color: P.paper, lineHeight: 1.1 }}>
            Upload Receipt
          </div>
          <RcMono size={8.5} color={P.gold} tracking="0.16em" style={{ marginTop: 3, display: 'block' }}>
            {done ? 'Financials · Filed' : `Financials · Step ${idx + 1} of ${RC_STEPS.length}`}
          </RcMono>
        </div>
        <CAMonogram size={20} color={P.paper} stroke={1.6} />
      </div>

      {/* step rail */}
      <div style={{ display: 'flex', padding: '0 18px 12px', gap: 8 }}>
        {RC_STEPS.map((s, i) => {
          const state = done ? 'done' : i < idx ? 'done' : i === idx ? 'active' : 'todo';
          return (
            <div key={s.id} style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
              <div style={{
                height: 3,
                background: state === 'todo' ? P.graphite : P.gold,
                opacity: state === 'active' ? 1 : state === 'done' ? 0.55 : 1,
              }} />
              <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                <RcMono size={7.5} color={state === 'active' ? P.paper : state === 'done' ? P.gold : P.mute} tracking="0.12em">
                  {state === 'done' ? '✓ ' : `${i + 1} · `}{s.label}
                </RcMono>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// STEP 1 — CAPTURE
// ─────────────────────────────────────────────────────────────────────
function CaptureStep({ onExtract }) {
  const [picked, setPicked] = useRc(false);
  const methods = [
    { id: 'photo',  icon: 'gallery',  label: 'Photo' },
    { id: 'camera', icon: 'camera',   label: 'Camera' },
    { id: 'pdf',    icon: 'FileText', label: 'PDF' },
    { id: 'email',  icon: 'Mail',     label: 'Email-in' },
  ];
  const fields = ['Vendor', 'Date', 'Currency', 'Line items', 'Tax / VAT', 'Totals'];

  return (
    <div className="proto-scroll" style={{ flex: 1, overflow: 'auto', background: P.ink }} data-screen-label="rc-capture">
      <div style={{ padding: '18px 22px 12px' }}>
        <div style={{ fontFamily: T.display, fontWeight: 700, fontSize: 32, lineHeight: 0.92, letterSpacing: '-0.02em', color: P.paper }}>
          CAPTURE THE<br />SOURCE
        </div>
        <div style={{ fontFamily: T.body, fontSize: 12.5, color: P.mute, marginTop: 10, lineHeight: 1.5, maxWidth: 320 }}>
          Drop any receipt or invoice — restoration shop, engine builder, parts supplier,
          eBay, hardware store, foreign vendor. The archive reads it. <span style={{ color: P.bone }}>You never type a total.</span>
        </div>
      </div>

      {/* drop / picked state */}
      <div style={{ padding: '6px 22px 14px' }}>
        {!picked ? (
          <button onClick={() => setPicked(true)} className="rc-drop">
            <span className="rc-drop__ring">
              <Icon name="Upload" size={24} color={P.gold} strokeWidth={1.5} />
            </span>
            <div style={{ fontFamily: T.display, fontSize: 18, fontWeight: 600, color: P.paper, marginTop: 12 }}>Drag &amp; drop a document</div>
            <div style={{ fontFamily: T.body, fontSize: 12, color: P.mute, marginTop: 5 }}>or choose a source below</div>
            <RcMono size={8.5} color={P.slate} style={{ marginTop: 14, display: 'block' }}>JPG · PNG · HEIC · PDF · UP TO 25MB</RcMono>
          </button>
        ) : (
          <div style={{ border: `1px solid ${P.gold}`, background: P.graphite, padding: 14, display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 46, height: 58, flexShrink: 0, overflow: 'hidden', border: `1px solid ${P.slate}` }}>
              <div style={{ transform: 'scale(0.34)', transformOrigin: 'top left', width: 294 }}>
                <ReceiptDocument compact />
              </div>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: T.body, fontSize: 13, color: P.paper, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{RECEIPT.intake.file}</div>
              <RcMono size={8.5} color={P.mute} style={{ marginTop: 4, display: 'block' }}>{RECEIPT.intake.size} · READY TO READ</RcMono>
            </div>
            <button onClick={() => setPicked(false)} aria-label="Remove" style={{
              background: 'transparent', border: `1px solid ${P.slate}`, color: P.mute,
              width: 30, height: 30, cursor: 'pointer', flexShrink: 0,
              fontFamily: T.mono, fontSize: 14,
            }}>×</button>
          </div>
        )}
      </div>

      {/* methods */}
      <div style={{ padding: '0 22px 18px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
          {methods.map(m => (
            <button key={m.id} onClick={() => setPicked(true)} style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
              padding: '14px 4px', cursor: 'pointer', background: 'transparent',
              border: `1px solid ${P.slate}`,
            }}>
              <Icon name={m.icon} size={20} color={P.paper} strokeWidth={1.5} />
              <RcMono size={8} color={P.paper} tracking="0.12em">{m.label}</RcMono>
            </button>
          ))}
        </div>
      </div>

      {/* what gets read */}
      <RowRule>WHAT THE ARCHIVE READS</RowRule>
      <div style={{ padding: '12px 22px 18px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1, background: P.slate, border: `1px solid ${P.slate}` }}>
          {fields.map(f => (
            <div key={f} style={{ background: P.ink, padding: '11px 12px', display: 'flex', alignItems: 'center', gap: 9 }}>
              <span style={{ width: 5, height: 5, borderRadius: 999, background: P.gold }} />
              <RcMono size={9} color={P.paper} tracking="0.12em">{f}</RcMono>
            </div>
          ))}
        </div>
      </div>

      {/* preserve original — a guarantee, not a toggle */}
      <div style={{ padding: '0 22px 18px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 13, background: P.graphite, borderLeft: `2px solid ${P.gold}`, padding: '14px 16px' }}>
          <Icon name="archive" size={20} color={P.gold} strokeWidth={1.6} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: T.display, fontSize: 14, fontWeight: 600, color: P.paper }}>Original Always Preserved</div>
            <div style={{ fontFamily: T.body, fontSize: 11, color: P.mute, marginTop: 3, lineHeight: 1.45 }}>
              The source document is filed in the Vault, untouched, as a permanent archival record.
            </div>
          </div>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 5, flexShrink: 0,
            background: P.gold, color: P.ink, padding: '5px 8px',
            fontFamily: T.mono, fontSize: 8, fontWeight: 700, letterSpacing: '0.12em',
          }}>
            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
            ON
          </span>
        </div>
      </div>

      {/* CTA */}
      <div style={{ padding: '0 22px 14px' }}>
        <button onClick={onExtract} disabled={!picked} style={{
          width: '100%', height: 52,
          background: picked ? P.gold : P.graphite,
          border: `1px solid ${picked ? P.gold : P.slate}`,
          color: picked ? P.ink : P.mute, cursor: picked ? 'pointer' : 'not-allowed',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          fontFamily: T.mono, fontSize: 11, fontWeight: 700, letterSpacing: '0.22em', textTransform: 'uppercase',
        }}>
          <Icon name="spark" size={16} color={picked ? P.ink : P.mute} strokeWidth={2} />
          Read this receipt
        </button>
        {!picked && <RcMono size={8.5} color={P.mute} style={{ display: 'block', textAlign: 'center', marginTop: 10 }}>Add a document to continue</RcMono>}
      </div>
      <div style={{ height: 18 }} />
    </div>
  );
}

// ── scanning overlay ────────────────────────────────────────────────────
function ScanningStep({ onDone }) {
  const fields = ['Vendor', 'Date', 'Currency', 'Line items', 'Tax / VAT', 'Totals'];
  React.useEffect(() => {
    const t = setTimeout(onDone, 2100);
    return () => clearTimeout(t);
  }, []);
  return (
    <div className="proto-scroll" style={{ flex: 1, overflow: 'auto', background: P.ink }} data-screen-label="rc-scanning">
      <div style={{ padding: '20px 22px 8px' }}>
        <RcMono size={9} color={P.gold} style={{ display: 'block' }}>● READING DOCUMENT</RcMono>
        <div style={{ fontFamily: T.display, fontWeight: 700, fontSize: 28, lineHeight: 0.95, letterSpacing: '-0.015em', color: P.paper, marginTop: 8 }}>
          EXTRACTING<br />THE RECORD
        </div>
      </div>
      <div style={{ padding: '14px 22px 16px' }}>
        <div className="rc-scanwrap">
          <ReceiptDocument />
          <div className="rc-scanline" />
        </div>
      </div>
      <div style={{ padding: '0 22px 24px' }}>
        <div style={{ display: 'grid', gap: 8 }}>
          {fields.map((f, i) => (
            <div key={f} className="rc-scanfield" style={{ animationDelay: `${i * 0.26}s` }}>
              <span className="rc-scanfield__dot" />
              <RcMono size={9.5} color={P.paper} tracking="0.14em">{f}</RcMono>
              <span className="rc-scanfield__check">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={P.gold} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
              </span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ReceiptDocument, ReceiptHeader, CaptureStep, ScanningStep, RcMono, Avatar, ConfTag, RC_STEPS });
