// ─────────────────────────────────────────────────────────────────────
// CONTRIBUTOR — secondary actions (Note · Photos · Videos · Documents).
//
// Mocked, deliberately. They share the same capture → submit spine as the
// receipt flow so the experience feels whole, but without extraction or
// review machinery. Each ends in the same "Submitted for review" handoff.
// ─────────────────────────────────────────────────────────────────────

const { useState: useCS } = React;

const STUB_CONFIG = {
  note: {
    eyebrow: 'Add Note', headline: ['JOT IT', 'DOWN'],
    intro: 'Capture progress, a finding, or context while it\u2019s fresh.',
    noteFirst: true, noteLabel: 'Your note', notePlaceholder: 'What happened, what you found, what\u2019s next…',
    sources: null, submit: 'Submit Note',
  },
  photos: {
    eyebrow: 'Upload Photos', headline: ['SHOW THE', 'WORK'],
    intro: 'Document condition and progress. Add as many as you need.',
    sources: [{ icon: 'camera', label: 'Camera' }, { icon: 'gallery', label: 'Photos' }],
    dropLabel: 'Add photos', dropHint: 'JPG · PNG · HEIC', submit: 'Submit Photos',
  },
  videos: {
    eyebrow: 'Upload Videos', headline: ['CAPTURE IT', 'RUNNING'],
    intro: 'Walkarounds, a running engine, a road test — show it in motion.',
    sources: [{ icon: 'Video', label: 'Record' }, { icon: 'gallery', label: 'Library' }],
    dropLabel: 'Add videos', dropHint: 'MP4 · MOV · up to 2GB', submit: 'Submit Videos',
  },
  documents: {
    eyebrow: 'Upload Documents', headline: ['FILE THE', 'PAPERWORK'],
    intro: 'Manuals, warranties, inspection reports, certificates.',
    sources: [{ icon: 'FileText', label: 'Files' }, { icon: 'camera', label: 'Scan' }],
    dropLabel: 'Add documents', dropHint: 'PDF · JPG · PNG', submit: 'Submit Documents',
  },
};
Object.assign(STUB_CONFIG, { document: STUB_CONFIG.documents });

// Shared header (mirrors the receipt top bar).
function CsTopBar({ eyebrow, onBack }) {
  return (
    <div style={{
      padding: '10px 18px 12px', background: P.ink, flex: '0 0 auto',
      display: 'flex', alignItems: 'center', gap: 12, borderBottom: `1px solid ${P.graphite}`,
    }}>
      <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 }}>{eyebrow}</div>
        <RcMono size={8.5} color={P.gold} tracking="0.16em" style={{ marginTop: 3, display: 'block' }}>{CONTRIBUTOR.collection}</RcMono>
      </div>
      <CAMonogram size={20} color={P.paper} stroke={1.6} />
    </div>
  );
}

// Generic confirmation for a stub submission.
function StubSubmittedOverlay({ what, onClose }) {
  const node = (
    <div style={{ position: 'absolute', inset: 0, zIndex: 98, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(10,10,11,0.85)', backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)' }} />
      <div style={{ position: 'relative', width: '100%', background: P.graphite, border: `1px solid ${P.gold}`, padding: 22, animation: 'sheetIn .25s cubic-bezier(.2,.7,.3,1)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span style={{ width: 38, height: 38, borderRadius: 999, border: `1px solid ${P.gold}`, background: 'rgba(184,144,85,0.1)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="Send" size={18} color={P.gold} strokeWidth={1.9} />
          </span>
          <div>
            <Eyebrow color={P.gold}>SUBMITTED FOR REVIEW</Eyebrow>
            <div style={{ fontFamily: T.display, fontSize: 22, fontWeight: 700, color: P.paper, marginTop: 5, letterSpacing: '-0.015em', lineHeight: 1 }}>Handed Off</div>
          </div>
        </div>
        <div style={{ fontFamily: T.body, fontSize: 12.5, color: P.bone, marginTop: 14, lineHeight: 1.55 }}>
          Your {what} {what.endsWith('s') ? 'are' : 'is'} now with <span style={{ color: P.paper, fontWeight: 600 }}>{CONTRIBUTOR.manager}</span> for review.
        </div>
        <button onClick={onClose} style={{ width: '100%', height: 48, marginTop: 18, background: P.gold, border: `1px solid ${P.gold}`, color: P.ink, fontFamily: T.mono, fontSize: 10, fontWeight: 700, letterSpacing: '0.2em', textTransform: 'uppercase', cursor: 'pointer' }}>Done</button>
      </div>
    </div>
  );
  const stage = (typeof document !== 'undefined') ? document.getElementById('contrib-stage') : null;
  return stage ? ReactDOM.createPortal(node, stage) : node;
}

function ContribSimpleFlow({ kind, vehicles = [], onBack, onClose }) {
  const cfg = STUB_CONFIG[kind] || STUB_CONFIG.note;
  const [count, setCount] = useCS(0);     // mock "files added"
  const [note, setNote] = useCS('');
  const [submitted, setSubmitted] = useCS(false);
  const [assignedId, setAssignedId] = useCS(null);
  const [assignOpen, setAssignOpen] = useCS(false);
  const pool = (typeof vehiclePool === 'function') ? vehiclePool(vehicles) : vehicles;
  const assignedVehicle = assignedId ? pool.find(v => v.id === assignedId) : null;

  const hasContent = (cfg.noteFirst ? note.trim().length > 0 : count > 0) && (cfg.noteFirst || !!assignedId);
  const what = cfg.noteFirst ? 'note' : cfg.eyebrow.split(' ').pop().toLowerCase();

  return (
    <React.Fragment>
      <CsTopBar eyebrow={cfg.eyebrow} onBack={onBack} />
      <div className="proto-scroll" style={{ flex: 1, overflow: 'auto', background: P.ink }} data-screen-label={`contrib-${kind}`}>
        <div style={{ padding: '18px 22px 12px' }}>
          <div style={{ fontFamily: T.display, fontWeight: 700, fontSize: 30, lineHeight: 0.95, letterSpacing: '-0.02em', color: P.paper }}>{cfg.headline[0]}<br />{cfg.headline[1]}</div>
          <div style={{ fontFamily: T.body, fontSize: 12.5, color: P.mute, marginTop: 10, lineHeight: 1.5 }}>{cfg.intro}</div>
        </div>

        {/* upload sources (non-note) */}
        {cfg.sources && (
          <React.Fragment>
            <div style={{ padding: '6px 22px 14px' }}>
              <div style={{ border: `1px solid ${count > 0 ? P.gold : P.slate}`, background: P.graphite }}>
                <div style={{ display: 'grid', gridTemplateColumns: `repeat(${cfg.sources.length}, 1fr)` }}>
                  {cfg.sources.map((m, i) => (
                    <button key={m.label} onClick={() => setCount(c => c + (kind === 'photos' ? 3 : 1))} style={{
                      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, padding: '18px 4px', cursor: 'pointer',
                      background: P.graphite, border: 'none', borderLeft: i > 0 ? `1px solid ${P.slate}` : 'none', color: P.paper,
                    }}>
                      <Icon name={m.icon} size={24} color={P.gold} strokeWidth={1.5} />
                      <RcMono size={9} color={P.paper} tracking="0.14em">{m.label}</RcMono>
                    </button>
                  ))}
                </div>
              </div>
            </div>

            {count > 0 ? (
              <div style={{ padding: '0 22px 16px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, background: P.graphite, border: `1px solid ${P.gold}`, padding: '13px 14px' }}>
                  <Icon name="Paperclip" size={18} color={P.gold} strokeWidth={1.7} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontFamily: T.body, fontSize: 13, color: P.paper, fontWeight: 500 }}>{count} {what}{count === 1 ? '' : ''} ready</div>
                    <RcMono size={8} color={P.mute} tracking="0.1em" style={{ marginTop: 3, display: 'block' }}>{cfg.dropHint}</RcMono>
                  </div>
                  <button onClick={() => setCount(0)} aria-label="Clear" style={{ width: 28, height: 28, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'transparent', border: 'none', cursor: 'pointer' }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={P.gold} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18" /><path d="M6 6l12 12" /></svg>
                  </button>
                </div>
              </div>
            ) : (
              <div style={{ padding: '0 22px 16px' }}>
                <div style={{ border: `1px dashed ${P.slate}`, padding: '18px 16px', textAlign: 'center' }}>
                  <RcMono size={9} color={P.mute} tracking="0.04em" style={{ textTransform: 'none', letterSpacing: '0.02em' }}>{cfg.dropLabel} — {cfg.dropHint}</RcMono>
                </div>
              </div>
            )}
          </React.Fragment>
        )}

        {/* note */}
        <div style={{ padding: cfg.noteFirst ? '6px 22px 8px' : '0 22px 8px' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 9 }}>
            <RcMono size={9} color={P.mute} tracking="0.18em">{cfg.noteLabel || 'Note'}</RcMono>
            {!cfg.noteFirst && <RcMono size={8} color={P.slate} tracking="0.14em">Optional</RcMono>}
          </div>
          <div style={{ border: `1px solid ${P.slate}`, background: P.graphite }}>
            <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={cfg.noteFirst ? 4 : 2}
              placeholder={cfg.notePlaceholder || 'Add context for the manager…'}
              style={{ width: '100%', resize: 'vertical', minHeight: cfg.noteFirst ? 110 : 58, boxSizing: 'border-box', background: P.ink, border: 'none', outline: 'none', color: P.paper, fontFamily: T.body, fontSize: 13, lineHeight: 1.5, padding: '12px 12px' }} />
          </div>
        </div>

        {/* which vehicle this submission belongs to — the same assignment
            pattern used everywhere else, incl. Collection Manager review */}
        {!cfg.noteFirst && (
          <div style={{ padding: '14px 22px 8px' }}>
            <VehicleAssignRow vehicle={assignedVehicle} label="VEHICLE" onChange={() => setAssignOpen(true)} />
          </div>
        )}

        {/* submit */}
        <div style={{ padding: '14px 22px 14px' }}>
          <button onClick={() => hasContent && setSubmitted(true)} disabled={!hasContent} style={{
            width: '100%', height: 52, background: hasContent ? P.gold : P.graphite, border: `1px solid ${hasContent ? P.gold : P.slate}`,
            color: hasContent ? P.ink : P.mute, cursor: hasContent ? 'pointer' : 'not-allowed',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            fontFamily: T.mono, fontSize: 11, fontWeight: 700, letterSpacing: '0.2em', textTransform: 'uppercase',
          }}>
            <Icon name="Send" size={16} color={hasContent ? P.ink : P.mute} strokeWidth={2} />
            {cfg.submit}
          </button>
          <div style={{ display: 'inline-flex', width: '100%', justifyContent: 'center', alignItems: 'center', gap: 8, marginTop: 12 }}>
            <span style={{ width: 5, height: 5, background: P.gold }} />
            <RcMono size={8} color={P.mute} tracking="0.14em">Goes to {CONTRIBUTOR.manager}'s review queue</RcMono>
          </div>
        </div>
        <div style={{ height: 14 }} />
      </div>

      {submitted && <StubSubmittedOverlay what={what + (cfg.noteFirst ? '' : 's')} onClose={() => { setSubmitted(false); onClose && onClose(); }} />}
      {assignOpen && (
        <VehicleAssignSheet
          vehicles={vehicles}
          currentId={assignedId}
          title="ASSIGN VEHICLE"
          subtitle={cfg.eyebrow}
          confirmLabel="Assign"
          onAssign={setAssignedId}
          onClose={() => setAssignOpen(false)}
        />
      )}
    </React.Fragment>
  );
}

Object.assign(window, { ContribSimpleFlow, StubSubmittedOverlay });
