// ─────────────────────────────────────────────────────────────────────
// CONTRIBUTOR — COLLECTION LANDING + OPERATIONS MENU.
//
// Mirrors the Collection Manager experience: the Collection is the landing
// page, and the hamburger opens Operations — a full-screen menu of the
// actions a contributor is allowed to perform. There is no separate
// "Operations screen"; Operations IS the menu.
//
// Only Upload Expense is wired this iteration. The rest are placeholders.
// Notes are never a standalone action — they belong to the record being
// created (e.g. Upload Expense → optional note), so there is no Notes item.
// ─────────────────────────────────────────────────────────────────────

const { useState: useCO } = React;

// A single navigation row — mirrors the manager's OpRow rhythm.
function ContribOpRow({ icon, title, onClick, placeholder }) {
  return (
    <InkCard onClick={onClick} padding={12} style={{
      display: 'grid', gridTemplateColumns: '24px 1fr auto auto', gap: 10, alignItems: 'center',
    }}>
      <Icon name={icon} size={18} color={P.gold} strokeWidth={1.5} />
      <div style={{ fontFamily: T.display, fontSize: 14, fontWeight: 600, color: P.paper, minWidth: 0 }}>{title}</div>
      {placeholder
        ? <span style={{ fontFamily: T.mono, fontSize: 7.5, fontWeight: 600, letterSpacing: '0.16em', textTransform: 'uppercase', color: P.mute, border: `1px solid ${P.slate}`, padding: '3px 6px' }}>Planned</span>
        : <span />}
      <Icon name="arrow" size={16} color={P.gold} strokeWidth={1.4} />
    </InkCard>
  );
}

// Section divider that matches the operations menu (RowRule + grid of rows).
function ContribOpsSection({ label, children }) {
  return (
    <div>
      <div style={{ padding: '20px 0 4px' }}><RowRule>{label}</RowRule></div>
      <div style={{ padding: '12px 22px 10px', display: 'grid', gap: 5 }}>{children}</div>
    </div>
  );
}

// ── OPERATIONS MENU ────────────────────────────────────────────────────
// The contributor's command center. Same structure as the manager menu,
// pared down to the actions a contributor is allowed to take.
function ContribOpsMenu({ onClose, onAction }) {
  return (
    <React.Fragment>
      {/* Sticky header — monogram + wordmark + close */}
      <div style={{
        padding: '14px 22px 8px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        flex: '0 0 auto', background: P.ink,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <CAMonogram size={20} color={P.paper} stroke={1.6} />
          <div style={{ fontFamily: T.display, fontSize: 14, fontWeight: 700, letterSpacing: '0.06em', color: P.paper }}>COLLECTOR / ARCHIVES</div>
        </div>
        <button onClick={onClose} aria-label="Close operations menu" style={{
          width: 38, height: 38, flexShrink: 0, borderRadius: 999, cursor: 'pointer',
          background: 'transparent', border: `1px solid ${P.gold}`, color: P.gold,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg className="ops-x" width="18" height="18" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" strokeWidth="1.9" strokeLinecap="round">
            <line x1="6" y1="6" x2="18" y2="18" />
            <line x1="18" y1="6" x2="6" y2="18" />
          </svg>
        </button>
      </div>

      <div className="proto-scroll" style={{ flex: 1, overflow: 'auto', background: P.ink }} data-screen-label="contrib-ops-menu">
        <div style={{ padding: '20px 22px 4px', display: 'grid', gap: 5 }}>
          <ContribOpRow icon="Inbox"   title="Complete Tasks" placeholder onClick={() => onAction('tasks')} />
          <ContribOpRow icon="UserCog" title="Manage Account" placeholder onClick={() => onAction('account')} />
        </div>

        <ContribOpsSection label="Financials">
          <ContribOpRow icon="Receipt" title="Upload Expense" onClick={() => onAction('expense')} />
        </ContribOpsSection>

        <ContribOpsSection label="Documents">
          <ContribOpRow icon="FileText" title="Upload Document" onClick={() => onAction('document')} />
        </ContribOpsSection>

        <ContribOpsSection label="Media">
          <ContribOpRow icon="gallery" title="Upload Photos" onClick={() => onAction('photos')} />
          <ContribOpRow icon="Video"   title="Upload Videos" onClick={() => onAction('videos')} />
        </ContribOpsSection>

        <div style={{ padding: '8px 22px 28px', display: 'flex', alignItems: 'center', gap: 10 }}>
          <span style={{ width: 5, height: 5, background: P.gold, flexShrink: 0 }} />
          <div style={{ fontFamily: T.mono, fontSize: 9, letterSpacing: '0.18em', textTransform: 'uppercase', color: P.mute, lineHeight: 1.6 }}>
            Capture the evidence · submit for review
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

// ── PLACEHOLDER SCREEN ──────────────────────────────────────────────────
// A consistent "coming soon" surface for the actions not yet built. Same
// top-bar chrome as every other operations screen, so the structure is
// already in place for the real flow to drop in.
function ContribPlaceholder({ eyebrow, title, note, onBack }) {
  return (
    <React.Fragment>
      <div style={{
        padding: '10px 18px 12px', background: P.ink,
        display: 'flex', alignItems: 'center', gap: 12,
        borderBottom: `1px solid ${P.graphite}`, flex: '0 0 auto',
      }}>
        <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 }}>{title}</div>
          <div style={{ fontFamily: T.mono, fontSize: 8.5, letterSpacing: '0.16em', color: P.gold, marginTop: 3 }}>{eyebrow}</div>
        </div>
        <CAMonogram size={20} color={P.paper} stroke={1.6} />
      </div>

      <div className="proto-scroll" style={{ flex: 1, overflow: 'auto', background: P.ink, display: 'flex', alignItems: 'center', justifyContent: 'center' }} data-screen-label="contrib-placeholder">
        <div style={{ padding: '40px 32px', textAlign: 'center', maxWidth: 320 }}>
          <span style={{
            width: 56, height: 56, borderRadius: 999, border: `1px solid ${P.slate}`,
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20,
            background: 'rgba(255,255,255,0.02)',
          }}>
            <Icon name="Hammer" size={22} color={P.mute} strokeWidth={1.5} />
          </span>
          <div style={{ fontFamily: T.display, fontSize: 24, fontWeight: 700, color: P.paper, letterSpacing: '-0.015em', lineHeight: 1.05 }}>Coming Soon</div>
          <div style={{ fontFamily: T.body, fontSize: 12.5, color: P.mute, marginTop: 12, lineHeight: 1.55 }}>{note}</div>
        </div>
      </div>
    </React.Fragment>
  );
}

// ── OPERATIONS FLOW SHELL ───────────────────────────────────────────────
// Full-screen overlay portalled onto the contributor phone stage. Mirrors
// the manager's OperationsFlow, routing each menu action to its screen.
function ContribOperations({ vehicles = [], onClose, initialView = 'menu' }) {
  const [view, setView] = useCO(initialView); // menu | expense | tasks | account | document | photos | videos
  const [closing, setClosing] = useCO(false);

  const requestClose = () => {
    if (closing) return;
    setClosing(true);
    setTimeout(() => { onClose && onClose(); }, 240);
  };

  const handleAction = (id) => setView(id);
  const backToMenu = () => setView('menu');

  const PLACEHOLDERS = {
    tasks:    { eyebrow: 'General', title: 'Complete Tasks', note: 'Tasks assigned to you by the collection manager will appear here — things to capture, confirm, or follow up on.' },
    account:  { eyebrow: 'General', title: 'Manage Account', note: 'Your profile, the collection you contribute to, and notification settings will live here.' },
  };
  const SIMPLE_FLOWS = ['document', 'photos', 'videos'];

  const node = (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 95, background: P.ink,
      animation: `${closing ? 'opsFadeOut' : 'opsFadeIn'} .24s ease forwards`,
    }}>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', background: P.ink }}>
        <DeviceTopSpacer bg={P.ink} />
        {view === 'menu' && (
          <ContribOpsMenu onClose={requestClose} onAction={handleAction} />
        )}
        {view === 'expense' && (
          <ReceiptFlow vehicles={vehicles} submit onBack={backToMenu} onClose={requestClose} />
        )}
        {SIMPLE_FLOWS.includes(view) && (
          <ContribSimpleFlow kind={view} vehicles={vehicles} onBack={backToMenu} onClose={requestClose} />
        )}
        {PLACEHOLDERS[view] && (
          <ContribPlaceholder {...PLACEHOLDERS[view]} onBack={backToMenu} />
        )}
        <DeviceBottomSpacer bg={P.ink} />
      </div>

      <style>{`
        @keyframes opsFadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes opsFadeOut { from { opacity: 1; } to { opacity: 0; } }
        @keyframes opsXDraw { from { stroke-dashoffset: 18; } to { stroke-dashoffset: 0; } }
        .ops-x line { stroke-dasharray: 18; stroke-dashoffset: 18; animation: opsXDraw .32s cubic-bezier(.5,0,.2,1) forwards; }
        .ops-x line:nth-child(2) { animation-delay: .12s; }
      `}</style>
    </div>
  );

  const stage = (typeof document !== 'undefined') ? document.getElementById('contrib-stage') : null;
  return stage ? ReactDOM.createPortal(node, stage) : node;
}

// ── COLLECTION LANDING ──────────────────────────────────────────────────
// The default landing page. Mirrors the manager's Garage masthead + stat
// strip + search/filter + vehicle cards, scoped to a contributor: no Add,
// no editing, no dollar valuation. The hamburger opens Operations.
function ContribCollection({ vehicles = [] }) {
  const [query, setQuery] = useCO('');
  const [filter, setFilter] = useCO('All');
  const [showOps, setShowOps] = useCO(false);
  const [opsView, setOpsView] = useCO('menu');
  const openOps = (view) => { setOpsView(view); setShowOps(true); };

  const activeVehicles = vehicles.filter(v => v.status !== 'Sold' && v.status !== 'Archived');
  const soldVehicles = vehicles.filter(v => v.status === 'Sold' || v.status === 'Archived');
  const counts = { All: vehicles.length, Active: activeVehicles.length, Sold: soldVehicles.length };

  let list = vehicles.filter(v => {
    if (filter === 'Active') return v.status !== 'Sold' && v.status !== 'Archived';
    if (filter === 'Sold') return v.status === 'Sold' || v.status === 'Archived';
    return true;
  });
  const q = query.trim().toLowerCase();
  if (q) {
    list = list.filter(v => `${v.year} ${v.make} ${v.model} ${v.nickname}`.toLowerCase().includes(q));
  }
  list = [...list].sort((a, b) =>
    (a.make || '').localeCompare(b.make || '') ||
    (a.model || '').localeCompare(b.model || '') ||
    (a.year || 0) - (b.year || 0)
  );

  const collection = (typeof CONTRIBUTOR !== 'undefined' ? CONTRIBUTOR.collection : 'The Collection');

  return (
    <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', background: P.ink, color: P.paper, position: 'relative' }}>
      {/* App header — monogram + hamburger (opens Operations) */}
      <div style={{ padding: '14px 22px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flex: '0 0 auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <CAMonogram size={20} color={P.paper} stroke={1.6} />
          <div style={{ fontFamily: T.display, fontSize: 14, fontWeight: 700, letterSpacing: '0.06em' }}>COLLECTOR / ARCHIVES</div>
        </div>
        <button onClick={() => openOps('menu')} aria-label="Open operations menu" style={{
          width: 38, height: 38, flexShrink: 0, borderRadius: 999, cursor: 'pointer',
          background: 'transparent', border: `1px solid ${P.gold}`, color: P.paper,
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4,
        }}>
          <span style={{ width: 16, height: 1.6, background: P.gold, display: 'block' }} />
          <span style={{ width: 16, height: 1.6, background: P.gold, display: 'block' }} />
          <span style={{ width: 16, height: 1.6, background: P.gold, display: 'block' }} />
        </button>
      </div>

      <div className="proto-scroll" style={{ flex: 1, overflow: 'auto' }}>
        {/* Masthead + stats */}
        <div style={{ padding: '14px 22px 18px' }}>
          <div style={{ fontFamily: T.display, fontWeight: 700, fontSize: 46, lineHeight: 0.88, letterSpacing: '-0.02em' }}>THE<br/>COLLECTION</div>
          <Eyebrow color={P.gold} style={{ display: 'block', marginTop: 12 }}>Managed by {(typeof CONTRIBUTOR !== 'undefined' ? CONTRIBUTOR.manager : 'Jeff Smith')}</Eyebrow>
        </div>

        {/* Search */}
        <div style={{ padding: '0 22px 12px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', border: `1px solid ${P.slate}`, background: P.graphite }}>
            <Icon name="search" size={14} color={P.mute} />
            <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search"
              style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none', color: P.paper, fontFamily: T.body, fontSize: 13 }} />
            {query && (
              <button onClick={() => setQuery('')} style={{ background: 'transparent', border: 'none', color: P.gold, cursor: 'pointer', fontFamily: T.mono, fontSize: 14 }}>×</button>
            )}
          </div>
        </div>

        {/* Filter */}
        <div style={{ padding: '0 22px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
          <div style={{ display: 'inline-flex', border: `1px solid ${P.slate}` }}>
            {['All', 'Active', 'Sold'].map((f, i) => {
              const on = filter === f;
              return (
                <button key={f} onClick={() => setFilter(f)} style={{
                  padding: '9px 14px', background: on ? P.paper : 'transparent', color: on ? P.ink : P.paper,
                  border: 'none', borderLeft: i > 0 ? `1px solid ${P.slate}` : 'none',
                  fontFamily: T.mono, fontSize: 9, fontWeight: 600, letterSpacing: '0.16em', textTransform: 'uppercase', cursor: 'pointer',
                  display: 'inline-flex', gap: 6, alignItems: 'center',
                }}>
                  {f}<span style={{ color: on ? P.gold : P.mute }}>{counts[f]}</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* Cards — display only for a contributor */}
        <div style={{ padding: '0 22px 8px' }}>
          {list.length === 0 ? (
            <div style={{ padding: '48px 16px', textAlign: 'center', fontFamily: T.mono, fontSize: 10, color: P.mute, letterSpacing: '0.16em', textTransform: 'uppercase' }}>No vehicles match.</div>
          ) : list.map(v => (
            <VehicleCard key={v.id} v={v} onOpen={() => {}} />
          ))}
        </div>

        <div style={{ height: 12 }} />
      </div>

      {showOps && (
        <ContribOperations vehicles={vehicles} initialView={opsView} onClose={() => setShowOps(false)} />
      )}
    </div>
  );
}

Object.assign(window, { ContribCollection, ContribOperations, ContribOpsMenu });
