// Proto shell — header, section tabs, bottom nav.
// All chrome that lives outside the active screen.

const { useState, useMemo, useEffect, useRef } = React;

// Concours palette pulled from the design system.
const P = DIRECTIONS.concours.palette;
const T = DIRECTIONS.concours.type;

// ─────────────────────────────────────────────────────────────────────
// ACTION SHEET — mobile bottom sheet (replaces dropdown menus). Matches
// the Add Vehicle / Add Photos sheets. Portals to the phone stage so it
// overlays the full screen. items: [{ label, icon, danger, action }]
// ─────────────────────────────────────────────────────────────────────

function ActionSheet({ eyebrow, title, items, onClose }) {
  const node = (
    <div style={{ position: 'absolute', inset: 0, zIndex: 96 }}>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, background: 'rgba(10,10,11,0.8)',
        backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)',
        animation: 'sheetFade .2s ease',
      }} />
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        background: P.graphite, color: P.paper,
        borderTop: `1px solid ${P.gold}`, padding: '14px 22px 34px',
        animation: 'sheetIn .25s cubic-bezier(.2,.7,.3,1)',
      }}>
        <div style={{ width: 40, height: 4, background: P.slate, margin: '0 auto 16px' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
          <div style={{ minWidth: 0 }}>
            {eyebrow && <Eyebrow color={P.gold}>{eyebrow}</Eyebrow>}
            {title && <div style={{
              fontFamily: T.display, fontSize: 24, fontWeight: 700, color: P.paper,
              marginTop: 6, letterSpacing: '-0.015em',
            }}>{title}</div>}
          </div>
          <button onClick={onClose} style={{
            background: 'transparent', border: `1px solid ${P.slate}`, color: P.paper,
            padding: '6px 10px', cursor: 'pointer', fontFamily: T.mono, fontSize: 9,
            fontWeight: 600, letterSpacing: '0.2em', textTransform: 'uppercase', flexShrink: 0,
          }}>CLOSE</button>
        </div>
        <div style={{ display: 'grid', gap: 8 }}>
          {items.map((it) => (
            <button key={it.label} onClick={() => { onClose(); it.action && it.action(); }} style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 14, padding: '15px 16px',
              background: P.ink, border: `1px solid ${it.danger ? P.signal : P.slate}`, cursor: 'pointer',
              color: it.danger ? P.signal : P.paper, textAlign: 'left',
            }}>
              <Icon name={it.icon} size={18} color={it.danger ? P.signal : P.gold} strokeWidth={1.6} />
              <span style={{
                fontFamily: T.mono, fontSize: 11, fontWeight: 600,
                letterSpacing: '0.16em', textTransform: 'uppercase',
              }}>{it.label}</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
  const stage = (typeof document !== 'undefined') ? document.getElementById('proto-stage') : null;
  return stage ? ReactDOM.createPortal(node, stage) : node;
}

// ─────────────────────────────────────────────────────────────────────
// HEADER — vehicle context (back · nickname · menu)
// ─────────────────────────────────────────────────────────────────────

function ProtoHeader({ vehicle, onBack, onEdit, onDelete }) {
  const [menu, setMenu] = React.useState(false);
  return (
    <div style={{
      padding: '10px 18px 12px',
      background: P.ink,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      borderBottom: `1px solid ${P.graphite}`,
      position: 'relative',
    }}>
      <button onClick={onBack} aria-label="Back to collection" 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={{ textAlign: 'left', flex: 1, minWidth: 0, marginLeft: 12 }}>
        <div style={{
          fontFamily: T.display, fontWeight: 600, fontSize: 14,
          letterSpacing: '0.02em', color: P.paper, lineHeight: 1.1,
        }}>
          {vehicle.year} {vehicle.make} {vehicle.model}
        </div>
        <div style={{
          fontFamily: T.mono, fontSize: 8, letterSpacing: '0.24em',
          textTransform: 'uppercase', color: P.gold, marginTop: 3,
        }}>
          "{vehicle.nickname}"
        </div>
      </div>

      <button onClick={() => setMenu(m => !m)} aria-label="Vehicle menu" style={{
        background: 'transparent', border: 'none', padding: 6,
        color: P.paper, cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" strokeWidth="2" strokeLinecap="round">
          <circle cx="12" cy="5" r="1.2" /><circle cx="12" cy="12" r="1.2" /><circle cx="12" cy="19" r="1.2" />
        </svg>
      </button>

      {/* Action sheet (mobile) */}
      {menu && (
        <ActionSheet
          eyebrow={`${vehicle.year} · ${vehicle.make.toUpperCase()}`}
          title={vehicle.model.toUpperCase()}
          onClose={() => setMenu(false)}
          items={[
            { label: 'Edit details', icon: 'wrench', action: () => onEdit && onEdit(vehicle) },
            { label: 'Share record', icon: 'share', action: () => {} },
            { label: 'Remove from collection', icon: 'flag', danger: true, action: () => onDelete && onDelete(vehicle) },
          ]}
        />
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// SECTION TABS — horizontal scroll, sticky under header
// ─────────────────────────────────────────────────────────────────────

function ProtoSectionTabs({ active, onChange, sections = SECTIONS }) {
  return (
    <div className="proto-scroll" style={{
      background: P.ink,
      borderBottom: `1px solid ${P.graphite}`,
      overflowX: 'auto', overflowY: 'hidden',
      flex: '0 0 auto',
    }}>
      <div style={{ display: 'flex', padding: '0 14px', gap: 4, minWidth: 'max-content' }}>
        {sections.map(s => {
          const on = s.id === active;
          return (
            <button key={s.id}
              onClick={() => onChange(s.id)}
              style={{
                background: 'transparent', border: 'none', padding: '14px 10px 12px',
                cursor: 'pointer',
                position: 'relative', flex: '0 0 auto',
                fontFamily: T.mono, fontSize: 10, fontWeight: 600,
                letterSpacing: '0.2em', textTransform: 'uppercase',
                color: on ? P.paper : P.mute,
                transition: 'color .15s',
              }}>
              {s.label}
              <div style={{
                position: 'absolute', left: 10, right: 10, bottom: 6,
                height: 2,
                background: on ? P.gold : 'transparent',
                transition: 'background .15s',
              }} />
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// BOTTOM NAV — app-level 5 tabs
// ─────────────────────────────────────────────────────────────────────

function ProtoBottomNav({ onGarage }) {
  // Static — represents the broader app. In the prototype we live inside
  // "Garage" since we're viewing a specific vehicle.
  const items = [
    { icon: 'garage',      label: 'Garage',   on: true,  action: onGarage },
    { icon: 'hammer',      label: 'Auctions', on: false },
    { icon: 'compass',     label: 'Explore',  on: false },
    { icon: 'archive',     label: 'Archive',  on: false },
    { icon: 'certificate', label: 'Vault',    on: false },
  ];
  return (
    <div style={{
      background: P.ink,
      borderTop: `1px solid ${P.graphite}`,
      padding: '10px 0 6px',
      display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)',
      flex: '0 0 auto',
    }}>
      {items.map(i => (
        <button key={i.label} onClick={i.action} style={{
          background: 'transparent', border: 'none', padding: 4, cursor: i.action ? 'pointer' : 'default',
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
        }}>
          <Icon name={i.icon} size={20} color={i.on ? P.paper : P.mute}
            strokeWidth={i.on ? 1.8 : 1.4} />
          <div style={{
            fontFamily: T.mono, fontSize: 7, letterSpacing: '0.16em',
            textTransform: 'uppercase', color: i.on ? P.paper : P.mute,
          }}>{i.label}</div>
          {i.on && <div style={{
            width: 4, height: 4, background: P.gold, marginTop: 1,
          }} />}
        </button>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// SHARED PRIMITIVES — used across screens
// ─────────────────────────────────────────────────────────────────────

// Editorial section opener.
function ScreenIntro({ eyebrow, title, sub, right }) {
  return (
    <div style={{
      padding: '22px 22px 18px',
      display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
    }}>
      <div>
        <Eyebrow color={P.gold}>{eyebrow}</Eyebrow>
        <div style={{
          fontFamily: T.display, fontSize: 38, fontWeight: 700,
          lineHeight: 0.92, letterSpacing: '-0.015em',
          color: P.paper, marginTop: 8,
        }}>{title}</div>
        {sub && <div style={{
          fontFamily: T.body, fontSize: 12, color: P.mute, marginTop: 8,
          maxWidth: 260, lineHeight: 1.45,
        }}>{sub}</div>}
      </div>
      {right}
    </div>
  );
}

// Editorial rule label.
function RowRule({ children }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10, padding: '0 22px',
    }}>
      <div style={{
        fontFamily: T.mono, fontSize: 9, letterSpacing: '0.22em',
        textTransform: 'uppercase', color: P.mute, whiteSpace: 'nowrap',
      }}>{children}</div>
      <div style={{ flex: 1, height: 1, background: P.graphite }} />
    </div>
  );
}

// Card on the ink ground — graphite fill, gold rule.
function InkCard({ children, accent = false, padding = 18, style = {}, onClick }) {
  return (
    <div onClick={onClick} style={{
      background: P.graphite,
      borderLeft: accent ? `2px solid ${P.gold}` : '2px solid transparent',
      padding,
      cursor: onClick ? 'pointer' : 'default',
      ...style,
    }}>{children}</div>
  );
}

// Status chip
function StatusChip({ label, on = false, severity }) {
  const map = {
    soon:  { bg: P.signal,   fg: P.paper },
    watch: { bg: P.gold,     fg: P.ink   },
    ok:    { bg: P.graphite, fg: P.paper },
  };
  const c = on ? { bg: P.paper, fg: P.ink } : (map[severity] || map.ok);
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '6px 10px',
      background: c.bg, color: c.fg,
      fontFamily: T.mono, fontSize: 9, fontWeight: 600,
      letterSpacing: '0.18em', textTransform: 'uppercase',
    }}>{label}</span>
  );
}

// Canonical vehicle status label — the dot-pill used on the landing page.
// Use this everywhere a vehicle's status is shown so the platform stays
// consistent. Active states: gold pill + ink dot. Sold/Archived: dark
// translucent pill with gold border.
function VehicleStatusChip({ status }) {
  const sold = status === 'Sold' || status === 'Archived';
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 10px',
      background: sold ? 'rgba(10,10,11,0.7)' : P.gold,
      color: sold ? P.gold : P.ink,
      border: sold ? `1px solid ${P.gold}` : 'none',
      backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
      fontFamily: T.mono, fontSize: 9, fontWeight: 600,
      letterSpacing: '0.18em', textTransform: 'uppercase', whiteSpace: 'nowrap',
    }}>
      {!sold && <span style={{ width: 5, height: 5, background: P.ink, borderRadius: 3 }} />}
      {status}
    </span>
  );
}

// Spec strip (key / value pairs in a row)
function SpecStrip({ items, cols, dark = true }) {
  const c = dark ? P.paper : P.ink;
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: `repeat(${cols || items.length}, 1fr)`,
      gap: 14, padding: '14px 22px',
      borderTop: `1px solid ${dark ? P.graphite : P.line}`,
      borderBottom: `1px solid ${dark ? P.graphite : P.line}`,
    }}>
      {items.map((it, i) => (
        <div key={i}>
          <Eyebrow color={dark ? P.mute : P.slate}>{it.label}</Eyebrow>
          <div style={{
            fontFamily: T.display, fontSize: 15, fontWeight: 600,
            marginTop: 4, color: c, letterSpacing: '-0.005em',
          }}>{it.value}</div>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, {
  P, T,
  ProtoHeader, ProtoSectionTabs, ProtoBottomNav,
  ScreenIntro, RowRule, InkCard, StatusChip, VehicleStatusChip, SpecStrip, ActionSheet,
});
