// ReturnScribe — navigation chrome + form controls for the interactive prototype
// All consume the theme object `t`.

// ─────────────────────────────────────────────────────────────
// NavBar — back chevron + centered title + optional trailing
// ─────────────────────────────────────────────────────────────
function NavBar({ t, title, onBack, trailing, large }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: '10px 12px 8px', minHeight: 44, position: 'relative',
    }}>
      {onBack && (
        <PressScale as="button" scale={0.9} onClick={onBack} style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          display: 'flex', alignItems: 'center', gap: 1, padding: '4px 6px 4px 2px',
          color: t.accent,
        }}>
          <Icon name="chevron.left" size={22} color={t.accent} weight={2.4}/>
        </PressScale>
      )}
      <div style={{
        flex: 1, textAlign: 'center', color: t.text1,
        ...applyType(RSType.headline), whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
      }}>{title}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4, minWidth: onBack ? 34 : 0, justifyContent: 'flex-end' }}>
        {trailing}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Bottom Sheet — scrim + slide-up panel (rounded top, drag handle)
// ─────────────────────────────────────────────────────────────
function Sheet({ t, open, onClose, title, children, trailing, maxHeight = 720 }) {
  const [mounted, setMounted] = React.useState(open);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    if (open) { setMounted(true); requestAnimationFrame(() => requestAnimationFrame(() => setShown(true))); }
    else { setShown(false); const id = setTimeout(() => setMounted(false), 280); return () => clearTimeout(id); }
  }, [open]);
  if (!mounted) return null;
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 80 }}>
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, background: t.scrim,
        opacity: shown ? 1 : 0, transition: 'opacity 280ms ease',
      }}/>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        maxHeight, background: t.canvas,
        borderRadius: '20px 20px 0 0',
        transform: shown ? 'translateY(0)' : 'translateY(100%)',
        transition: 'transform 320ms cubic-bezier(.22,.61,.36,1)',
        display: 'flex', flexDirection: 'column',
        boxShadow: '0 -8px 40px rgba(0,0,0,0.28)',
        overflow: 'hidden',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0 2px', flexShrink: 0 }}>
          <div style={{ width: 36, height: 5, borderRadius: 99, background: t.text3, opacity: 0.4 }}/>
        </div>
        {(title || trailing) && (
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '6px 16px 12px', borderBottom: `0.5px solid ${t.border}`, flexShrink: 0,
          }}>
            <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: t.accent, ...applyType(RSType.body) }}>Cancel</button>
            <span style={{ color: t.text1, ...applyType(RSType.headline) }}>{title}</span>
            <div style={{ minWidth: 52, textAlign: 'right' }}>{trailing || <span style={{ width: 52, display: 'inline-block' }}/>}</div>
          </div>
        )}
        <div style={{ overflowY: 'auto', WebkitOverflowScrolling: 'touch', padding: '4px 0 24px' }}>
          {children}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Modal Cover — full-screen slide-up (paywall, consent, scan)
// ─────────────────────────────────────────────────────────────
function ModalCover({ t, open, children, z = 90 }) {
  const [mounted, setMounted] = React.useState(open);
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    if (open) { setMounted(true); requestAnimationFrame(() => requestAnimationFrame(() => setShown(true))); }
    else { setShown(false); const id = setTimeout(() => setMounted(false), 320); return () => clearTimeout(id); }
  }, [open]);
  if (!mounted) return null;
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: z, background: t.canvas,
      transform: shown ? 'translateY(0)' : 'translateY(100%)',
      transition: 'transform 360ms cubic-bezier(.22,.61,.36,1)',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      {children}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Action Menu — iOS context menu popover (anchored top-right)
// ─────────────────────────────────────────────────────────────
function ActionMenu({ t, open, onClose, items, anchor = 'right' }) {
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    if (open) requestAnimationFrame(() => setShown(true)); else setShown(false);
  }, [open]);
  if (!open) return null;
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 85 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0 }}/>
      <div style={{
        position: 'absolute', top: 88, [anchor]: 14, width: 230,
        transformOrigin: anchor === 'right' ? 'top right' : 'top left',
        transform: shown ? 'scale(1)' : 'scale(0.86)',
        opacity: shown ? 1 : 0,
        transition: 'transform 200ms cubic-bezier(.22,.61,.36,1), opacity 160ms ease',
      }}>
        <div style={{
          borderRadius: 14, overflow: 'hidden',
          background: t === RSTokens.dark ? 'rgba(44,46,49,0.82)' : 'rgba(250,250,250,0.86)',
          backdropFilter: 'blur(28px) saturate(180%)', WebkitBackdropFilter: 'blur(28px) saturate(180%)',
          border: `0.5px solid ${t.glassBorder}`,
          boxShadow: '0 12px 40px rgba(0,0,0,0.30)',
        }}>
          {items.map((it, i) => {
            const hasSel = items.some(x => x.selected != null);
            return (
            <button key={i} onClick={() => { onClose(); it.onClick && it.onClick(); }} style={{
              width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              gap: 12, padding: '13px 16px', border: 'none', cursor: 'pointer',
              background: 'transparent',
              borderTop: i ? `0.5px solid ${t.border}` : 'none',
              color: it.danger ? t.danger : t.text1, ...applyType(RSType.body),
            }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                {hasSel && <Icon name="check" size={15} weight={2.6}
                  color={it.selected ? (it.danger ? t.danger : t.text1) : 'transparent'}/>}
                <span>{it.label}</span>
              </span>
              <Icon name={it.icon} size={18} color={it.danger ? t.danger : t.text1}/>
            </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Form field row — label + editable value (text/number/date/select)
// ─────────────────────────────────────────────────────────────
function Field({ t, label, value, onChange, type = 'text', placeholder, isLast, edited, prefix, options, onPick }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10, padding: '11px 16px', minHeight: 50, position: 'relative',
    }}>
      <span style={{ color: t.text2, ...applyType(RSType.body), width: 110, flexShrink: 0 }}>{label}</span>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 6 }}>
        {edited && <span style={{
          ...applyType(RSType.caption), color: t.accent, fontWeight: 700,
          background: t.accentDim, padding: '2px 7px', borderRadius: 99, textTransform: 'uppercase', letterSpacing: 0.4,
        }}>Edited</span>}
        {options ? (
          <button onClick={onPick} style={{
            background: 'none', border: 'none', cursor: 'pointer',
            color: t.text1, ...applyType(RSType.body), display: 'flex', alignItems: 'center', gap: 4,
          }}>
            {value}<Icon name="chevron.down" size={13} color={t.text3} weight={2.2}/>
          </button>
        ) : (
          <div style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            {prefix && <span style={{ color: t.text2, ...applyType(RSType.body) }}>{prefix}</span>}
            <input value={value} placeholder={placeholder} inputMode={type === 'number' ? 'decimal' : undefined}
              onChange={e => onChange && onChange(e.target.value)}
              style={{
                border: 'none', outline: 'none', background: 'transparent', textAlign: 'right',
                color: t.text1, ...applyType(RSType.body), width: '100%', minWidth: 0,
                fontFamily: RSFont.sys,
              }}/>
          </div>
        )}
      </div>
      {!isLast && <div style={{ position: 'absolute', left: 16, right: 16, bottom: 0, height: 0.5, background: t.border }}/>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Stepper — qty control
// ─────────────────────────────────────────────────────────────
function Stepper({ t, value, onChange, min = 1 }) {
  const btn = (label, fn, disabled) => (
    <button onClick={fn} disabled={disabled} style={{
      width: 30, height: 30, border: 'none', cursor: disabled ? 'default' : 'pointer',
      background: 'transparent', color: disabled ? t.text3 : t.accent,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 20, fontWeight: 500,
    }}>{label}</button>
  );
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', background: t.surface2,
      borderRadius: 8, border: `0.5px solid ${t.border}`,
    }}>
      {btn('−', () => onChange(Math.max(min, value - 1)), value <= min)}
      <span style={{ minWidth: 22, textAlign: 'center', color: t.text1, ...applyType(RSType.subhead), fontWeight: 600, ...RSTabular }}>{value}</span>
      {btn('+', () => onChange(value + 1))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Toggle switch (iOS)
// ─────────────────────────────────────────────────────────────
function ToggleSwitch({ t, on, onChange, color }) {
  const c = color || t.success;
  return (
    <button onClick={() => onChange(!on)} style={{
      width: 51, height: 31, borderRadius: 99, border: 'none', cursor: 'pointer', padding: 2,
      background: on ? c : (t === RSTokens.dark ? '#39393D' : '#E9E9EA'),
      transition: 'background 220ms ease', flexShrink: 0, position: 'relative',
    }}>
      <span style={{
        display: 'block', width: 27, height: 27, borderRadius: 99, background: '#fff',
        transform: on ? 'translateX(20px)' : 'translateX(0)',
        transition: 'transform 220ms cubic-bezier(.34,1.4,.64,1)',
        boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
      }}/>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// Big segmented control (full-width, for paywall cadence etc.)
// ─────────────────────────────────────────────────────────────
function BigSegmented({ t, items, active, onChange, accent }) {
  const refs = React.useRef({});
  const wrap = React.useRef(null);
  const [box, setBox] = React.useState(null);
  React.useEffect(() => {
    const el = refs.current[active];
    if (!el) return;
    setBox({ left: el.offsetLeft, width: el.offsetWidth });
  }, [active, items.length]);
  return (
    <div ref={wrap} style={{
      display: 'flex', padding: 4, borderRadius: 12, background: t.surface2, position: 'relative',
    }}>
      {box && (
        <div style={{
          position: 'absolute', top: 4, bottom: 4, left: box.left, width: box.width,
          background: t.surface1, borderRadius: 9,
          boxShadow: '0 1px 3px rgba(0,0,0,0.12)',
          transition: 'left 280ms cubic-bezier(.34,1.2,.64,1), width 280ms cubic-bezier(.34,1.2,.64,1)',
        }}/>
      )}
      {items.map(it => {
        const a = it.id === active;
        return (
          <button key={it.id} ref={el => refs.current[it.id] = el} onClick={() => onChange(it.id)} style={{
            flex: 1, position: 'relative', zIndex: 1, height: 36, border: 'none', cursor: 'pointer',
            background: 'transparent', color: a ? t.text1 : t.text2,
            ...applyType(RSType.subhead), fontWeight: a ? 700 : 500,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
          }}>
            {it.label}
            {it.tag && <span style={{
              ...applyType(RSType.caption), fontWeight: 700, color: accent || t.accent,
              background: (accent || t.accent) + '22', padding: '1px 6px', borderRadius: 99,
            }}>{it.tag}</span>}
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Chevron row — generic tappable list row with chevron
// ─────────────────────────────────────────────────────────────
function ChevronRow({ t, icon, iconColor, title, subtitle, trailing, onClick, isLast, danger }) {
  return (
    <CardPress onClick={onClick}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', minHeight: 52, position: 'relative' }}>
        {icon && (
          <div style={{
            width: 30, height: 30, borderRadius: 8, background: (iconColor || t.text1) + '1A',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>
            <Icon name={icon} size={17} color={iconColor || t.text1}/>
          </div>
        )}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ color: danger ? t.danger : t.text1, ...applyType(RSType.body) }}>{title}</div>
          {subtitle && <div style={{ color: t.text2, ...applyType(RSType.footnote), marginTop: 1 }}>{subtitle}</div>}
        </div>
        {trailing && <span style={{ color: t.text2, ...applyType(RSType.subhead) }}>{trailing}</span>}
        {onClick && <Icon name="chevron.right" size={14} color={t.text3} weight={2.2}/>}
        {!isLast && <div style={{ position: 'absolute', left: icon ? 58 : 16, right: 16, bottom: 0, height: 0.5, background: t.border }}/>}
      </div>
    </CardPress>
  );
}

// ─────────────────────────────────────────────────────────────
// Scan progress bar — determinate sweep
// ─────────────────────────────────────────────────────────────
function ScanProgressBar({ t, pct, color }) {
  const c = color || t.accent;
  return (
    <div style={{ height: 6, borderRadius: 99, background: t.surface2, overflow: 'hidden', position: 'relative' }}>
      <div style={{
        height: '100%', width: pct + '%', background: c, borderRadius: 99,
        transition: 'width 400ms cubic-bezier(.4,0,.2,1)',
      }}/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Inline option picker sheet (for selects inside an edit sheet)
// ─────────────────────────────────────────────────────────────
function PickerSheet({ t, open, onClose, title, options, value, onPick }) {
  return (
    <Sheet t={t} open={open} onClose={onClose} title={title}>
      <div style={{ padding: '4px 0' }}>
        {options.map((opt, i) => (
          <button key={opt} onClick={() => { onPick(opt); onClose(); }} style={{
            width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '14px 18px', border: 'none', background: 'transparent', cursor: 'pointer',
            color: t.text1, ...applyType(RSType.body),
            borderTop: i ? `0.5px solid ${t.border}` : 'none',
          }}>
            <span>{opt}</span>
            {opt === value && <Icon name="check" size={18} color={t.accent} weight={2.4}/>}
          </button>
        ))}
      </div>
    </Sheet>
  );
}

Object.assign(window, {
  NavBar, Sheet, ModalCover, ActionMenu, Field, Stepper, ToggleSwitch,
  BigSegmented, ChevronRow, ScanProgressBar, PickerSheet,
});
