/* App chrome — minimal icon rail (left), top breadcrumb bar, report header. */

const IconRail = ({ active = 'reports', onThemeToggle, theme }) => {
  const items = [
    { id: 'home', icon: 'home', label: 'Dashboard', href: 'Dashboard.html' },
    { id: 'reports', icon: 'file', label: 'Reports', href: 'Reports.html' },
    { id: 'share', icon: 'share', label: 'Share Center', href: 'Share Center.html' },
    { id: 'team', icon: 'users', label: 'Team', href: 'Team.html' },
    { id: 'scheduled', icon: 'clock', label: 'Scheduled', href: 'Reports.html' },
  ];
  return (
    <aside style={{
      width: 52, minWidth: 52,
      background: 'var(--rc-rail-bg)',
      display: 'flex', flexDirection: 'column',
      position: 'relative',
      borderRight: '1px solid var(--rc-rail-border)',
      color: '#cbd5e1',
    }}>
      {/* Gradient accent stripe */}
      <div style={{
        position: 'absolute', left: 0, top: 0, bottom: 0, width: 3,
        background: 'linear-gradient(180deg, #22c55e, #14b8a6, #0891b2)',
        zIndex: 1,
      }} />
      {/* Logo — white-on-dark variant, sidebar is always dark */}
      <div style={{
        height: 52, display: 'flex', alignItems: 'center', justifyContent: 'center',
        borderBottom: '1px solid rgba(255,255,255,0.06)',
      }}>
        <img src="assets/mixshift-icon-white.svg" alt="MixShift" style={{ height: 28, width: 28 }} />
      </div>
      {/* Nav */}
      <nav style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, padding: '10px 0', flex: 1 }}>
        {items.map(n => {
          const on = n.id === active;
          const Tag = n.href ? 'a' : 'button';
          return (
            <Tag key={n.id} href={n.href} title={n.label} style={{
              width: 36, height: 36, borderRadius: 8, border: 0, cursor: 'pointer',
              background: on ? 'rgba(34,197,94,0.18)' : 'transparent',
              color: on ? '#fff' : '#64748b',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              position: 'relative', textDecoration: 'none',
            }}>
              <Icon name={n.icon} size={16} />
              {on && <span style={{ position: 'absolute', left: -2, top: 8, bottom: 8, width: 2, background: '#22c55e', borderRadius: 2 }} />}
            </Tag>
          );
        })}
      </nav>
      {/* Bottom */}
      <div style={{ padding: '10px 0', borderTop: '1px solid rgba(255,255,255,0.06)',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
        <button onClick={onThemeToggle} title="Theme" style={{
          width: 36, height: 36, borderRadius: 8, border: 0, background: 'transparent',
          color: '#64748b', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><Icon name={theme === 'dark' ? 'sun' : 'moon'} size={16} /></button>
        <div style={{
          width: 30, height: 30, borderRadius: 9999,
          background: 'var(--rc-green)', color: '#fff',
          fontSize: 11, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>JS</div>
      </div>
    </aside>
  );
};

const TopBar = ({ report, merchant, onClose, role, onReportTypeChange, onMerchantChange }) => {
  const roleLabel = {
    admin: 'Admin',
    editor: 'Editor',
    viewer: 'Viewer',
  }[role];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      background: 'var(--rc-card)', borderBottom: '1px solid var(--rc-border)',
      padding: '6px 14px', fontSize: 12, minHeight: 42, flexShrink: 0,
    }}>
      {/* Breadcrumb chain */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--rc-text)', fontWeight: 600 }}>
          <Icon name="file" size={13} />
          <span>Reports</span>
        </div>
        <span style={{ color: 'var(--rc-border)' }}>/</span>
        <BreadChip
          label={merchant.name}
          color="green"
          picker={{
            heading: 'Switch merchant',
            activeId: merchant.id,
            searchable: true,
            searchPlaceholder: 'Search merchants, marketplaces…',
            options: MERCHANTS.map(m => ({
              id: m.id,
              label: m.name,
              hint: `${m.marketplace} · ${m.platform}`,
              flagCode: m.marketShort,
              keywords: `${m.name} ${m.marketplace} ${m.marketShort} ${m.platform} ${m.currency}`,
            })),
            onSelect: (id) => onMerchantChange && onMerchantChange(id),
          }}
        />
        <BreadChip
          label={report.name}
          picker={{
            heading: 'Switch report type',
            activeId: report.id,
            options: Object.values(REPORT_TYPES).map(rt => ({
              id: rt.id, label: rt.name, hint: rt.platform,
            })),
            onSelect: (id) => onReportTypeChange && onReportTypeChange(id),
          }}
        />
      </div>
      {/* Right chrome */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
        <Pill tone={role === 'admin' ? 'dark' : role === 'editor' ? 'green' : 'ghost'} size="sm">
          <Icon name={role === 'viewer' ? 'eye' : 'lock'} size={10} />
          {roleLabel}
        </Pill>
        <div style={{ width: 1, height: 14, background: 'var(--rc-border)', margin: '0 6px' }} />
        <IconBtn name="search" title="Search" />
        <IconBtn name="refresh" title="Refresh" />
        <IconBtn name="bell" title="Notifications" />
        <CurrencyPicker />
      </div>
    </div>
  );
};

const BreadChip = ({ label, color, picker }) => {
  const [open, setOpen] = React.useState(false);
  const [query, setQuery] = React.useState('');
  const inputRef = React.useRef(null);
  const hasPicker = !!picker;
  const searchable = hasPicker && picker.searchable;

  React.useEffect(() => {
    if (open && searchable && inputRef.current) {
      const t = setTimeout(() => inputRef.current.focus(), 10);
      return () => clearTimeout(t);
    }
    if (!open) setQuery('');
  }, [open, searchable]);

  const filtered = React.useMemo(() => {
    if (!hasPicker) return [];
    const q = query.trim().toLowerCase();
    if (!q) return picker.options;
    return picker.options.filter(o => {
      const hay = `${o.label} ${o.hint || ''} ${o.keywords || ''}`.toLowerCase();
      return hay.includes(q);
    });
  }, [hasPicker, picker, query]);
  return (
    <span style={{ position: 'relative', display: 'inline-flex' }}>
      <button
        type="button"
        onClick={hasPicker ? () => setOpen(!open) : undefined}
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '3px 9px',
          background: color === 'green' ? 'color-mix(in srgb, var(--rc-green) 10%, transparent)' : 'var(--rc-chip-bg)',
          border: `1px solid ${color === 'green' ? 'color-mix(in srgb, var(--rc-green) 25%, transparent)' : 'var(--rc-border)'}`,
          borderRadius: 5,
          color: color === 'green' ? 'var(--rc-green-ink)' : 'var(--rc-text)',
          fontSize: 11, fontWeight: 500, lineHeight: 1.2,
          cursor: hasPicker ? 'pointer' : 'default',
          fontFamily: 'inherit',
        }}
      >
        <span style={{
          width: 5, height: 5, borderRadius: 9999,
          background: color === 'green' ? 'var(--rc-green)' : 'var(--rc-text-mute)',
        }} />
        {label}
        {hasPicker
          ? <Icon name="chevronDown" size={10} color="var(--rc-text-mute)" strokeWidth={2} />
          : <Icon name="x" size={10} color="var(--rc-text-mute)" strokeWidth={2} />
        }
      </button>
      {hasPicker && open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
          <div style={{
            position: 'absolute', top: 'calc(100% + 4px)', left: 0, zIndex: 41,
            background: 'var(--rc-card)', border: '1px solid var(--rc-border)',
            borderRadius: 8, boxShadow: '0 12px 32px -8px rgba(15,23,42,0.22)',
            minWidth: 280, maxWidth: 360, padding: 4,
            display: 'flex', flexDirection: 'column',
          }}>
            <div style={{
              fontSize: 10, color: 'var(--rc-text-mute)', fontWeight: 500,
              padding: '6px 10px 4px', textTransform: 'uppercase', letterSpacing: '0.05em',
            }}>{picker.heading || 'Switch'}</div>
            {searchable && (
              <div style={{
                display: 'flex', alignItems: 'center', gap: 6,
                margin: '2px 4px 4px', padding: '6px 8px',
                border: '1px solid var(--rc-border)', borderRadius: 6,
                background: 'var(--rc-hover)',
              }}>
                <Icon name="search" size={12} color="var(--rc-text-mute)" />
                <input
                  ref={inputRef}
                  value={query}
                  onChange={e => setQuery(e.target.value)}
                  placeholder={picker.searchPlaceholder || 'Search…'}
                  style={{
                    flex: 1, border: 0, outline: 'none', background: 'transparent',
                    fontFamily: 'inherit', fontSize: 12, color: 'var(--rc-text)',
                    padding: 0, minWidth: 0,
                  }}
                />
                {query && (
                  <button
                    onClick={() => { setQuery(''); inputRef.current && inputRef.current.focus(); }}
                    style={{
                      border: 0, background: 'transparent', padding: 0, cursor: 'pointer',
                      display: 'inline-flex', color: 'var(--rc-text-mute)',
                    }}
                    title="Clear"
                  >
                    <Icon name="x" size={12} />
                  </button>
                )}
              </div>
            )}
            <div style={{
              maxHeight: 320, overflowY: 'auto', overflowX: 'hidden',
              display: 'flex', flexDirection: 'column',
            }}>
              {filtered.length === 0 && (
                <div style={{
                  padding: '16px 10px', fontSize: 11, color: 'var(--rc-text-mute)',
                  textAlign: 'center',
                }}>No matches</div>
              )}
              {filtered.map(opt => {
                const on = opt.id === picker.activeId;
                return (
                  <button key={opt.id} onClick={() => { picker.onSelect(opt.id); setOpen(false); }}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 8, width: '100%',
                      padding: '8px 10px', background: on ? 'var(--rc-hover)' : 'transparent',
                      border: 0, borderRadius: 5, textAlign: 'left', cursor: 'pointer',
                      fontFamily: 'inherit', flexShrink: 0,
                    }}
                    onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--rc-hover)'; }}
                    onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent'; }}>
                    <span style={{ width: 14, display: 'inline-flex', justifyContent: 'center', flexShrink: 0 }}>
                      {on && <Icon name="check" size={12} color="var(--rc-green-ink)" strokeWidth={2.5} />}
                    </span>
                    {opt.flagCode && (
                      <span style={{
                        flexShrink: 0, display: 'inline-flex', alignItems: 'center',
                        justifyContent: 'center', width: 20,
                      }}>
                        <Flag code={opt.flagCode} size={18} radius={3} style={{ height: 13 }} />
                      </span>
                    )}
                    {opt.glyph && !opt.flagCode && (
                      <span style={{
                        fontSize: 16, lineHeight: 1, flexShrink: 0,
                        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                        width: 20,
                      }}>{opt.glyph}</span>
                    )}
                    <span style={{ display: 'flex', flexDirection: 'column', gap: 1, flex: 1, minWidth: 0 }}>
                      <span style={{
                        fontSize: 12, fontWeight: on ? 600 : 500, color: 'var(--rc-text)',
                        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                      }}>{opt.label}</span>
                      {opt.hint && <span style={{
                        fontSize: 10, color: 'var(--rc-text-mute)',
                        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                      }}>{opt.hint}</span>}
                    </span>
                  </button>
                );
              })}
            </div>
          </div>
        </>
      )}
    </span>
  );
};

/* Twemoji flag renderer — converts ISO-2 country short code (e.g. "US", "JP") to a CDN SVG.
   This bypasses the OS color-emoji font, so flags render identically on Win/Mac/Linux/ChromeOS. */
const TWEMOJI_BASE = 'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/svg';
const flagSvgUrl = (short) => {
  if (!short) return null;
  // EU handled specially
  if (short.toUpperCase() === 'EU') return `${TWEMOJI_BASE}/1f1ea-1f1fa.svg`;
  const A = 0x1F1E6; // regional indicator A
  const codes = short.toUpperCase().split('').map(ch => (A + (ch.charCodeAt(0) - 65)).toString(16));
  return `${TWEMOJI_BASE}/${codes.join('-')}.svg`;
};
const Flag = ({ code, size = 16, radius = 2, style }) => {
  const url = flagSvgUrl(code);
  if (!url) return null;
  return (
    <img
      src={url}
      alt={code}
      loading="lazy"
      style={{
        width: size, height: Math.round(size * 0.75), borderRadius: radius,
        objectFit: 'cover', display: 'inline-block', flexShrink: 0,
        boxShadow: '0 0 0 1px rgba(15,23,42,0.08)',
        ...style,
      }}
    />
  );
};

/* Top-bar currency picker — opens a dropdown listing currencies with live FX rates vs the active one. */
const CURRENCIES = [
  { code: 'USD', name: 'US Dollar',      short: 'US', flag: '🇺🇸', rate: 1.0000 },
  { code: 'EUR', name: 'Euro',           short: 'EU', flag: '🇪🇺', rate: 0.9200 },
  { code: 'GBP', name: 'British Pound',  short: 'GB', flag: '🇬🇧', rate: 0.7900 },
  { code: 'JPY', name: 'Japanese Yen',   short: 'JP', flag: '🇯🇵', rate: 155.42 },
  { code: 'CAD', name: 'Canadian Dollar',short: 'CA', flag: '🇨🇦', rate: 1.3750 },
  { code: 'AUD', name: 'Australian Dollar', short: 'AU', flag: '🇦🇺', rate: 1.5150 },
  { code: 'MXN', name: 'Mexican Peso',   short: 'MX', flag: '🇲🇽', rate: 17.18 },
  { code: 'INR', name: 'Indian Rupee',   short: 'IN', flag: '🇮🇳', rate: 83.22 },
  { code: 'BRL', name: 'Brazilian Real', short: 'BR', flag: '🇧🇷', rate: 5.08 },
  { code: 'SGD', name: 'Singapore Dollar', short: 'SG', flag: '🇸🇬', rate: 1.3480 },
  { code: 'CHF', name: 'Swiss Franc',    short: 'CH', flag: '🇨🇭', rate: 0.8950 },
  { code: 'SEK', name: 'Swedish Krona',  short: 'SE', flag: '🇸🇪', rate: 10.64 },
  { code: 'PLN', name: 'Polish Zloty',   short: 'PL', flag: '🇵🇱', rate: 3.98 },
  { code: 'AED', name: 'UAE Dirham',     short: 'AE', flag: '🇦🇪', rate: 3.6725 },
  { code: 'SAR', name: 'Saudi Riyal',    short: 'SA', flag: '🇸🇦', rate: 3.7500 },
];

const CurrencyPicker = () => {
  const [open, setOpen] = React.useState(false);
  const [base, setBase] = React.useState('USD');       // merchant/org default — the underlying data currency
  const [active, setActive] = React.useState('USD');    // display currency — what user wants to see
  const [basePickerOpen, setBasePickerOpen] = React.useState(false);
  const [query, setQuery] = React.useState('');
  const inputRef = React.useRef(null);
  const activeDef = CURRENCIES.find(c => c.code === active) || CURRENCIES[0];
  const baseDef = CURRENCIES.find(c => c.code === base) || CURRENCIES[0];

  // Rates of every row expressed relative to the *base* (not display).
  // Base rates in the table are vs USD; convert via: rateVsBase = rateVsUsd / baseRateVsUsd
  const rowsRel = React.useMemo(() => {
    const baseRate = baseDef.rate;
    return CURRENCIES.map(c => ({
      ...c,
      rel: c.rate / baseRate,
      delta: c.rate / baseRate > 1 ? 'up' : c.rate / baseRate < 1 ? 'down' : 'same',
    }));
  }, [baseDef]);

  const filtered = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return rowsRel;
    return rowsRel.filter(c =>
      `${c.code} ${c.name} ${c.short}`.toLowerCase().includes(q)
    );
  }, [rowsRel, query]);

  React.useEffect(() => {
    if (open && inputRef.current) {
      const t = setTimeout(() => inputRef.current.focus(), 10);
      return () => clearTimeout(t);
    }
    if (!open) { setQuery(''); setBasePickerOpen(false); }
  }, [open]);

  const ShortBadge = ({ short, big }) => (
    <span style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      width: big ? 28 : 18, height: big ? 28 : 16,
      borderRadius: big ? 6 : 4,
      background: big ? 'var(--rc-hover)' : 'var(--rc-chip-bg)',
      border: '1px solid var(--rc-border)',
      color: 'var(--rc-text-sub)',
      fontSize: big ? 10 : 9, fontWeight: 700, letterSpacing: '0.02em',
      flexShrink: 0,
    }}>{short}</span>
  );

  return (
    <div style={{ position: 'relative', display: 'inline-flex' }}>
      <button
        onClick={() => setOpen(!open)}
        title="Change display currency"
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '3px 10px 3px 10px', height: 24,
          borderRadius: 9999,
          border: '1px solid var(--rc-border)',
          background: 'var(--rc-card)',
          color: 'var(--rc-text)',
          fontSize: 11, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
          lineHeight: 1,
        }}>
        <span style={{ fontWeight: 600 }}>{activeDef.code}</span>
        <Flag code={activeDef.short} size={16} />
        <Icon name="chevronDown" size={10} color="var(--rc-text-mute)" />
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
          <div style={{
            position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 41,
            background: 'var(--rc-card)', border: '1px solid var(--rc-border)',
            borderRadius: 10, boxShadow: '0 16px 40px -10px rgba(15,23,42,0.28)',
            width: 340, display: 'flex', flexDirection: 'column',
            overflow: 'hidden',
          }}>
            {/* Header */}
            <div style={{ padding: '14px 14px 8px' }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--rc-text)', marginBottom: 2 }}>
                Currency
              </div>
              <div style={{ fontSize: 11, color: 'var(--rc-text-mute)' }}>
                Choose the base your data is stored in, then pick what to display.
              </div>
            </div>

            {/* Base currency row */}
            <div style={{ padding: '0 10px 10px' }}>
              <div style={{
                fontSize: 10, fontWeight: 600, color: 'var(--rc-text-mute)',
                textTransform: 'uppercase', letterSpacing: '0.06em',
                marginBottom: 4, paddingLeft: 4,
              }}>Base currency</div>
              <div style={{ position: 'relative' }}>
                <button
                  onClick={() => setBasePickerOpen(!basePickerOpen)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 10, width: '100%',
                    padding: '8px 10px',
                    border: '1px solid var(--rc-border)', borderRadius: 6,
                    background: 'var(--rc-hover)', cursor: 'pointer', fontFamily: 'inherit',
                    textAlign: 'left',
                  }}>
                  <Flag code={baseDef.short} size={22} radius={3} style={{ height: 16 }} />
                  <span style={{ display: 'flex', flexDirection: 'column', gap: 1, flex: 1, minWidth: 0 }}>
                    <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--rc-text)' }}>
                      {baseDef.name}
                    </span>
                    <span style={{ fontSize: 10, color: 'var(--rc-text-mute)', fontWeight: 500 }}>
                      {baseDef.code} · source data currency
                    </span>
                  </span>
                  <Icon name="chevronDown" size={11} color="var(--rc-text-mute)" />
                </button>
                {basePickerOpen && (
                  <div style={{
                    position: 'absolute', top: 'calc(100% + 4px)', left: 0, right: 0, zIndex: 2,
                    maxHeight: 200, overflowY: 'auto',
                    background: 'var(--rc-card)', border: '1px solid var(--rc-border)',
                    borderRadius: 6, boxShadow: '0 12px 28px -8px rgba(15,23,42,0.25)',
                    padding: 4,
                  }}>
                    {CURRENCIES.map(c => {
                      const on = c.code === base;
                      return (
                        <button
                          key={c.code}
                          onClick={() => { setBase(c.code); setBasePickerOpen(false); }}
                          style={{
                            display: 'flex', alignItems: 'center', gap: 8, width: '100%',
                            padding: '6px 8px', borderRadius: 4,
                            background: on ? 'var(--rc-hover)' : 'transparent',
                            border: 0, textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit',
                            flexShrink: 0,
                          }}
                          onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--rc-hover)'; }}
                          onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent'; }}
                        >
                          <Flag code={c.short} size={18} radius={2} style={{ height: 13 }} />
                          <span style={{
                            flex: 1, fontSize: 11, color: 'var(--rc-text)', fontWeight: on ? 600 : 500,
                            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                          }}>{c.name}</span>
                          <span style={{ fontSize: 10, color: 'var(--rc-text-mute)', fontWeight: 600 }}>{c.code}</span>
                          {on && <Icon name="check" size={11} color="var(--rc-green-ink)" strokeWidth={2.5} />}
                        </button>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>

            {/* Display currency section label */}
            <div style={{
              fontSize: 10, fontWeight: 600, color: 'var(--rc-text-mute)',
              textTransform: 'uppercase', letterSpacing: '0.06em',
              padding: '4px 14px 6px',
              borderTop: '1px solid var(--rc-border)',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              marginTop: 2, paddingTop: 10,
            }}>
              <span>Display as</span>
              <span style={{
                fontSize: 10, color: 'var(--rc-text-mute)',
                textTransform: 'none', letterSpacing: 0, fontWeight: 500,
              }}>
                rates vs {baseDef.code}
              </span>
            </div>
            {/* Search */}
            <div style={{ padding: '6px 10px 8px' }}>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 6,
                padding: '6px 8px',
                border: '1px solid var(--rc-border)', borderRadius: 6,
                background: 'var(--rc-hover)',
              }}>
                <Icon name="search" size={12} color="var(--rc-text-mute)" />
                <input
                  ref={inputRef}
                  value={query}
                  onChange={e => setQuery(e.target.value)}
                  placeholder="Search currencies…"
                  style={{
                    flex: 1, border: 0, outline: 'none', background: 'transparent',
                    fontFamily: 'inherit', fontSize: 12, color: 'var(--rc-text)',
                    padding: 0, minWidth: 0,
                  }}
                />
                {query && (
                  <button
                    onClick={() => { setQuery(''); inputRef.current && inputRef.current.focus(); }}
                    style={{
                      border: 0, background: 'transparent', padding: 0, cursor: 'pointer',
                      display: 'inline-flex', color: 'var(--rc-text-mute)',
                    }}
                    title="Clear"
                  >
                    <Icon name="x" size={12} />
                  </button>
                )}
              </div>
            </div>
            {/* List */}
            <div style={{
              maxHeight: 320, overflowY: 'auto', overflowX: 'hidden',
              display: 'flex', flexDirection: 'column', padding: '0 4px 4px',
            }}>
              {filtered.length === 0 && (
                <div style={{
                  padding: '16px 10px', fontSize: 11, color: 'var(--rc-text-mute)',
                  textAlign: 'center',
                }}>No matches</div>
              )}
              {filtered.map(c => {
                const on = c.code === active;        // selected for DISPLAY
                const isBaseRow = c.code === base;   // same as base → rate is trivially 1
                return (
                  <button
                    key={c.code}
                    onClick={() => { setActive(c.code); setOpen(false); }}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 10, width: '100%',
                      padding: '8px 10px', minHeight: 40,
                      background: on ? 'var(--rc-hover)' : 'transparent',
                      border: on ? '1px solid var(--rc-border)' : '1px solid transparent',
                      borderRadius: 8, textAlign: 'left', cursor: 'pointer',
                      fontFamily: 'inherit', flexShrink: 0,
                    }}
                    onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--rc-hover)'; }}
                    onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent'; }}
                  >
                    <Flag code={c.short} size={28} radius={4} style={{ height: 21 }} />
                    <span style={{ display: 'flex', flexDirection: 'column', gap: 1, flex: 1, minWidth: 0 }}>
                      <span style={{
                        display: 'inline-flex', alignItems: 'center', gap: 6,
                        fontSize: 12, fontWeight: 600, color: 'var(--rc-text)',
                        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                      }}>
                        {c.name}
                        {isBaseRow && (
                          <span style={{
                            fontSize: 9, fontWeight: 700, letterSpacing: '0.04em',
                            color: 'var(--rc-green-ink)',
                            background: 'color-mix(in srgb, var(--rc-green) 12%, transparent)',
                            border: '1px solid color-mix(in srgb, var(--rc-green) 30%, transparent)',
                            borderRadius: 3, padding: '1px 5px',
                            textTransform: 'uppercase',
                          }}>Base</span>
                        )}
                        {on && !isBaseRow && (
                          <Icon name="check" size={12} color="var(--rc-green-ink)" strokeWidth={2.5} />
                        )}
                      </span>
                      <span style={{
                        fontSize: 10, color: 'var(--rc-text-mute)', fontWeight: 500, letterSpacing: '0.02em',
                      }}>{c.code}</span>
                    </span>
                    {!isBaseRow && (
                      <span style={{
                        display: 'inline-flex', alignItems: 'center', gap: 4,
                        fontSize: 11, color: 'var(--rc-text-sub)', fontWeight: 500,
                        fontVariantNumeric: 'tabular-nums',
                        flexShrink: 0,
                      }}>
                        <span>1 {base} = {formatRate(c.rel)}</span>
                        <Icon
                          name={c.delta === 'up' ? 'arrowUp' : 'arrowDown'}
                          size={10}
                          color={c.delta === 'up' ? 'var(--rc-green-ink)' : 'var(--rc-text-mute)'}
                          strokeWidth={2.25}
                        />
                      </span>
                    )}
                  </button>
                );
              })}
            </div>
            {/* Footer */}
            <div style={{
              padding: '10px 14px',
              borderTop: '1px solid var(--rc-border)',
              background: 'var(--rc-hover)',
              fontSize: 10, color: 'var(--rc-text-mute)', textAlign: 'center',
              lineHeight: 1.45,
            }}>
              Exchange rates are updated in real-time. Rates may vary.
            </div>
          </div>
        </>
      )}
    </div>
  );
};

function formatRate(n) {
  if (!isFinite(n)) return '—';
  if (n >= 100) return n.toFixed(2);
  if (n >= 10)  return n.toFixed(2);
  if (n >= 1)   return n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');
  return n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');
}

/* RC-RPT3-SPADS-007 — compact inline campaign-type scope (replaces 40px segmented strip) */
const CampaignTypeSelect = ({ value, onChange }) => {
  const [open, setOpen] = React.useState(false);
  const OPTIONS = [
    { value: 'all', label: 'All campaigns', short: 'All' },
    { value: 'sp',  label: 'Sponsored Products', short: 'SP' },
    { value: 'sb',  label: 'Sponsored Brands',   short: 'SB' },
    { value: 'sd',  label: 'Sponsored Display',  short: 'SD' },
  ];
  const active = OPTIONS.find(o => o.value === value) || OPTIONS[0];
  return (
    <div style={{ position: 'relative', display: 'inline-flex' }}>
      <button
        onClick={() => setOpen(!open)}
        title="Filter by campaign type"
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 6, height: 22,
          padding: '0 8px', borderRadius: 9999,
          border: `1px solid ${value !== 'all' ? 'var(--rc-chart-1)' : 'var(--rc-border)'}`,
          background: value !== 'all'
            ? 'color-mix(in srgb, var(--rc-chart-1) 10%, var(--rc-card))'
            : 'var(--rc-card)',
          color: value !== 'all' ? 'var(--rc-chart-1)' : 'var(--rc-text-sub)',
          fontSize: 11, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
          lineHeight: 1,
        }}>
        <Icon name="filter" size={10} />
        <span>Campaign:</span>
        <span style={{ fontWeight: 600 }}>{active.short}</span>
        <Icon name="chevronDown" size={10} />
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
          <div style={{
            position: 'absolute', top: 'calc(100% + 4px)', left: 0, zIndex: 41,
            background: 'var(--rc-card)', border: '1px solid var(--rc-border)',
            borderRadius: 8, boxShadow: '0 12px 32px -8px rgba(15,23,42,0.22)',
            minWidth: 200, padding: 4,
          }}>
            {OPTIONS.map(opt => (
              <button
                key={opt.value}
                onClick={() => { onChange(opt.value); setOpen(false); }}
                style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  width: '100%', gap: 10, padding: '7px 10px', borderRadius: 6,
                  border: 'none', cursor: 'pointer', fontFamily: 'inherit',
                  background: opt.value === value
                    ? 'color-mix(in srgb, var(--rc-chart-1) 10%, transparent)'
                    : 'transparent',
                  color: 'var(--rc-text)', fontSize: 12, textAlign: 'left',
                }}
                onMouseEnter={e => { if (opt.value !== value) e.currentTarget.style.background = 'var(--rc-surface-sub)'; }}
                onMouseLeave={e => { if (opt.value !== value) e.currentTarget.style.background = 'transparent'; }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  <span style={{
                    width: 22, textAlign: 'center',
                    fontSize: 10, fontWeight: 700, letterSpacing: '0.02em',
                    color: opt.value === value ? 'var(--rc-chart-1)' : 'var(--rc-text-mute)',
                  }}>{opt.short}</span>
                  <span style={{ fontWeight: opt.value === value ? 600 : 400 }}>{opt.label}</span>
                </span>
                {opt.value === value && <Icon name="check" size={12} color="var(--rc-chart-1)" />}
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
};

/* RC-PAGE-003 — new report header: breadcrumb · merchant · platform · marketplace.
   RC-PAGE-004 — consistent type scale with the other pages. */
const ReportHeader = ({ report, merchant, onTabChange, activePage, onShare, onResetDefaults, onSaveDefaults, onCopyUrl,
  spadsCampaignType, setSpadsCampaignType,
  vendorDataView, setVendorDataView,
  namedViews, activeView, onSaveView, onSwitchView, onDeleteView,
  currentTweaks, viewUnsaved }) => {
  const tabs = [
    { id: 'time', label: 'Performance Over Time' },
    { id: 'range', label: 'Performance Over Range' },
    { id: 'metric', label: 'Performance by Metric' },
    { id: 'dimension', label: 'Performance by Dimension' },
  ];
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [scheduleOpen, setScheduleOpen] = React.useState(false);
  const [saveViewOpen, setSaveViewOpen] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(null), 2200); };
  return (
    <div style={{
      background: 'var(--rc-card)',
      borderBottom: '1px solid var(--rc-border)',
      padding: '18px 24px 0',
    }}>
      {/* Title + meta line */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14 }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, fontSize: 12, color: 'var(--rc-text-sub)' }}>
            <span>Reports</span>
            <Icon name="chevronRight" size={11} />
            <span style={{ color: 'var(--rc-text)', fontWeight: 500 }}>{merchant.name}</span>
            <Icon name="chevronRight" size={11} />
            <span>{merchant.platform}</span>
            <Icon name="chevronRight" size={11} />
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <Flag code={merchant.marketShort} size={14} radius={2} style={{ height: 10 }} />
              {merchant.marketplace}
            </span>
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
            <h1 style={{
              margin: 0, fontFamily: 'Poppins', fontSize: 22, fontWeight: 700,
              color: 'var(--rc-text)', letterSpacing: '-0.02em', lineHeight: 1.2,
            }}>{report.name}</h1>
            <Pill tone="green" size="sm">
              <span style={{ width: 5, height: 5, borderRadius: 9999, background: 'var(--rc-green)' }} />
              Saved
            </Pill>
            <span style={{ fontSize: 12, color: 'var(--rc-text-mute)' }}>Last updated 2 min ago</span>
            {/* RC-RPT3-SPADS-007 — Campaign type scope, inline compact select */}
            {report.id === 'spads' && setSpadsCampaignType && (
              <CampaignTypeSelect
                value={spadsCampaignType || 'all'}
                onChange={setSpadsCampaignType} />
            )}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <EditorOnly role={window.__role}>
            <button
              onClick={() => setSaveViewOpen(true)}
              title={viewUnsaved ? `Unsaved changes in "${activeView}"` : undefined}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 6, height: 28,
                padding: '0 10px', borderRadius: 6,
                border: `1px solid ${viewUnsaved ? '#f59e0b' : 'var(--rc-border)'}`,
                background: viewUnsaved
                  ? 'color-mix(in srgb, #f59e0b 10%, var(--rc-card))'
                  : 'var(--rc-card)',
                color: viewUnsaved ? '#b45309' : 'var(--rc-text)',
                fontSize: 12, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
              }}>
              <Icon name={activeView ? 'bookmark' : 'plus'} size={12} />
              {activeView ? `View: ${activeView}` : 'Save View'}
              {viewUnsaved && (
                <span style={{
                  display: 'inline-block', width: 6, height: 6, borderRadius: 9999,
                  background: '#f59e0b',
                }} />
              )}
            </button>
          </EditorOnly>
          <Btn icon="download" variant="outline" size="sm"
            onClick={() => {
              const sid = window.__rcToast && window.__rcToast.exportStarted({ scope: 'report PDF' });
              setTimeout(() => {
                window.__rcToast && window.__rcToast.dismiss(sid);
                if (Math.random() < 0.55) {
                  window.__rcToast.exportSucceeded({ scope: 'report', filename: 'report.pdf' });
                } else {
                  window.__rcToast.exportFailed({
                    scope: 'report',
                    detail: 'PDF rendering service timed out. This is usually transient — please try again.',
                    onRetry: () => {
                      const sid2 = window.__rcToast.exportStarted({ scope: 'report PDF' });
                      setTimeout(() => {
                        window.__rcToast.dismiss(sid2);
                        window.__rcToast.exportSucceeded({ scope: 'report', filename: 'report.pdf' });
                      }, 1200);
                    },
                  });
                }
              }, 1100);
            }}>Export</Btn>
          <EditorOnly role={window.__role}>
            <Btn icon="share" variant="primary" size="sm" onClick={onShare}>Share</Btn>
          </EditorOnly>
          <div style={{ position: 'relative' }}>
            <IconBtn name="moreH" title="More" onClick={() => setMenuOpen(!menuOpen)} active={menuOpen} />
            {menuOpen && (
              <>
                <div onClick={() => setMenuOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
                <div style={{
                  position: 'absolute', top: 'calc(100% + 4px)', right: 0, zIndex: 41,
                  background: 'var(--rc-card)', border: '1px solid var(--rc-border)',
                  borderRadius: 8, boxShadow: '0 12px 32px -8px rgba(15,23,42,0.22)',
                  minWidth: 230, padding: 4,
                }}>
                  <HeaderMenuItem icon="link" label="Copy shareable URL" sub="Deep-link to current view"
                    onClick={() => { onCopyUrl && onCopyUrl(); showToast('Link copied'); setMenuOpen(false); }} />
                  <EditorOnly role={window.__role}>
                    <HeaderMenuItem icon="clock" label="Schedule delivery" sub="Email PDF/XLSX on a cadence"
                      onClick={() => { setScheduleOpen(true); setMenuOpen(false); }} />
                  </EditorOnly>
                  {namedViews && Object.keys(namedViews).length > 0 && (
                    <>
                      <div style={{ height: 1, background: 'var(--rc-border-soft)', margin: '4px 0' }} />
                      <div style={{ padding: '4px 10px', fontSize: 10, fontWeight: 600,
                        color: 'var(--rc-text-mute)', letterSpacing: '0.05em', textTransform: 'uppercase' }}>
                        Named views
                      </div>
                      {Object.keys(namedViews).map(name => (
                        <HeaderMenuItem key={name}
                          icon={name === activeView ? 'check' : 'bookmark'}
                          label={name}
                          sub={name === activeView ? 'Active view' : 'Switch to this view'}
                          onClick={() => {
                            onSwitchView && onSwitchView(name);
                            showToast(`Switched to "${name}"`);
                            setMenuOpen(false);
                          }} />
                      ))}
                    </>
                  )}
                  <div style={{ height: 1, background: 'var(--rc-border-soft)', margin: '4px 0' }} />
                  <EditorOnly role={window.__role}>
                    <HeaderMenuItem icon="bookmark" label="Save current as default" sub="Saved for your account"
                      onClick={() => { onSaveDefaults && onSaveDefaults(); setMenuOpen(false); }} />
                  </EditorOnly>
                  <HeaderMenuItem icon="reset" label="Reset to defaults" sub="Report-type defaults"
                    onClick={() => { onResetDefaults && onResetDefaults(); showToast('Reset to defaults'); setMenuOpen(false); }} />
                </div>
              </>
            )}
          </div>
        </div>
      </div>

      {/* 4-page jump-to pills */}
      <div style={{ display: 'flex', gap: 2, marginTop: 8 }}>
        {tabs.map(t => {
          const on = t.id === activePage;
          return (
            <button key={t.id}
              onClick={() => {
                onTabChange && onTabChange(t.id);
                const el = document.getElementById(`rc-page-${t.id}`);
                const scroller = document.querySelector('[data-rc-scroll]') || document.scrollingElement;
                if (el && scroller) {
                  const top = el.getBoundingClientRect().top + scroller.scrollTop - 12;
                  scroller.scrollTo({ top, behavior: 'smooth' });
                }
              }}
              style={{
                padding: '9px 14px', border: 0, background: 'transparent',
                color: on ? 'var(--rc-text)' : 'var(--rc-text-sub)',
                fontSize: 13, fontWeight: on ? 600 : 500,
                borderBottom: `2px solid ${on ? 'var(--rc-green)' : 'transparent'}`,
                marginBottom: -1, cursor: 'pointer', fontFamily: 'inherit',
                transition: 'all 120ms',
              }}>{t.label}</button>
          );
        })}
      </div>
      {/* RC-RPT3-RSA-009 — Vendor data-view toggle (Mfg vs Sourcing). Retail only, vendors only. */}
      {report.id === 'retail' && merchant && merchant.isVendor && setVendorDataView && (
        <div style={{
          marginTop: 10, padding: '8px 12px',
          background: 'color-mix(in srgb, var(--rc-chart-2) 7%, var(--rc-card))',
          border: '1px solid var(--rc-border-soft)', borderRadius: 8,
          display: 'inline-flex', alignItems: 'center', gap: 10, flexWrap: 'wrap',
        }}>
          <span style={{ fontSize: 11, fontWeight: 500, color: 'var(--rc-text-sub)',
            display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <Icon name="package" size={11} /> Vendor data view:
          </span>
          <Segmented size="sm"
            tabs={[
              { value: 'mfg',      label: 'Manufacturing' },
              { value: 'sourcing', label: 'Sourcing' },
            ]}
            active={vendorDataView || 'mfg'}
            onChange={setVendorDataView} />
          <span style={{ fontSize: 10.5, color: 'var(--rc-text-sub)', lineHeight: 1.3, maxWidth: 360 }}>
            {(vendorDataView || 'mfg') === 'mfg'
              ? 'Shipped-to-Amazon — what you invoiced Amazon.'
              : 'Ordered-by-Amazon — what Amazon requested via POs.'}
          </span>
          <span style={{ fontSize: 10, color: 'var(--rc-text-mute)', fontStyle: 'italic' }}>
            vendor only
          </span>
        </div>
      )}
      {/* RC-RPT3-SPADS-007 — moved inline next to "Last updated" above */}
      {toast && (
        <div style={{
          position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)', zIndex: 200,
          background: '#111827', color: '#fff', padding: '10px 16px', borderRadius: 8,
          fontSize: 13, fontFamily: 'Inter', boxShadow: '0 12px 32px -8px rgba(0,0,0,0.4)',
          display: 'inline-flex', alignItems: 'center', gap: 8,
        }}>
          <Icon name="checkCircle" size={14} color="#34D399" />{toast}
        </div>
      )}
      {/* RC-RPT-040 — Schedule delivery modal */}
      {typeof ScheduleReportModal !== 'undefined' && (
        <ScheduleReportModal
          open={scheduleOpen}
          onClose={() => setScheduleOpen(false)}
          reportName={report.name}
          onSchedule={(payload) => showToast(`Scheduled · ${payload.cadence}`)}
        />
      )}
      {/* RC-RPT-062 — Save View modal (replaces window.prompt) */}
      {typeof SaveViewModal !== 'undefined' && (
        <SaveViewModal
          open={saveViewOpen}
          onClose={() => setSaveViewOpen(false)}
          activeView={activeView}
          namedViews={namedViews || {}}
          currentTweaks={currentTweaks || {}}
          onSave={(name) => {
            onSaveView && onSaveView(name);
            showToast(`View "${name}" saved`);
          }}
          onSwitch={(name) => {
            onSwitchView && onSwitchView(name);
            showToast(`Switched to "${name}"`);
          }}
          onDelete={(name) => {
            onDeleteView && onDeleteView(name);
            showToast(`View "${name}" deleted`);
          }}
        />
      )}
    </div>
  );
};

const HeaderMenuItem = ({ icon, label, sub, onClick }) => (
  <button onClick={onClick} style={{
    display: 'flex', alignItems: 'center', gap: 10, width: '100%',
    padding: '8px 10px', background: 'transparent', border: 0, borderRadius: 6,
    cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit',
  }}
    onMouseEnter={e => e.currentTarget.style.background = 'var(--rc-subtle)'}
    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
    <Icon name={icon} size={14} color="var(--rc-text-sub)" />
    <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
      <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--rc-text)' }}>{label}</span>
      {sub && <span style={{ fontSize: 10, color: 'var(--rc-text-mute)' }}>{sub}</span>}
    </div>
  </button>
);

/* RC-RPT-071 — role-based UI suppression. */
const useUserRole = (roleOverride) => {
  const role = roleOverride || window.__role || 'admin';
  return {
    platformRole: role === 'admin' ? 'platform_admin' : 'member',
    sharingPermission: role === 'viewer' ? 'view' : role === 'editor' ? 'edit' : 'own',
    canEdit: role !== 'viewer',
    canShare: role !== 'viewer',
    canDelete: role === 'admin',
  };
};
const AdminOnly = ({ role, children }) => { const r = useUserRole(role); return r.platformRole === 'platform_admin' ? children : null; };
const EditorOnly = ({ role, children }) => { const r = useUserRole(role); return r.canEdit ? children : null; };
const ViewerAllowed = ({ children }) => children;

Object.assign(window, { IconRail, TopBar, BreadChip, ReportHeader, useUserRole, AdminOnly, EditorOnly, ViewerAllowed });
