/* Page-level controls: date range, granularity, comparison, view-by.
   RC-PAGE-010 / RC-PAGE-012 / RC-PAGE-013 / RC-PAGE-030 / RC-PAGE-040 */

/* RC-PAGE-010 — 16-range canonical preset table (Week / Last Week / QTD / Last Quarter / Last Year) */
const DATE_PRESETS = [
  { value: 'wtd',       label: 'Week-to-Date' },
  { value: 'lastWeek',  label: 'Last Week' },
  { value: 'mtd',       label: 'Month-to-Date' },
  { value: 'lastMonth', label: 'Last Month' },
  { value: 'qtd',       label: 'Quarter-to-Date' },
  { value: 'lastQuarter', label: 'Last Quarter' },
  { value: 'l7',        label: 'Last 7 Days' },
  { value: 'l30',       label: 'Last 30 Days' },
  { value: 'l60',       label: 'Last 60 Days' },
  { value: 'l90',       label: 'Last 90 Days' },
  { value: 'l6m',       label: 'Last 6 Months' },
  { value: 't12m',      label: 'T-12 Months' },
  { value: 't12mPlusMtd', label: 'T-12 Months + MTD' },
  { value: 'ytd',       label: 'Year-to-Date' },
  { value: 'lastYear',  label: 'Last Year' },
  { value: 'custom',    label: 'Custom Range' },
];

const DATE_RANGES = {
  wtd:         '04/20/2026 → 04/22/2026',
  lastWeek:    '04/13/2026 → 04/19/2026',
  mtd:         '04/01/2026 → 04/22/2026',
  lastMonth:   '03/01/2026 → 03/31/2026',
  qtd:         '04/01/2026 → 04/22/2026',
  lastQuarter: '01/01/2026 → 03/31/2026',
  l7:          '04/16/2026 → 04/22/2026',
  l30:         '03/23/2026 → 04/22/2026',
  l60:         '02/21/2026 → 04/22/2026',
  l90:         '01/22/2026 → 04/22/2026',
  l6m:         '10/22/2025 → 04/22/2026',
  t12m:        '04/01/2025 → 03/31/2026',
  t12mPlusMtd: '04/01/2025 → 04/22/2026',
  ytd:         '01/01/2026 → 04/22/2026',
  lastYear:    '01/01/2025 → 12/31/2025',
  custom:      '02/15/2026 → 04/15/2026',
};

const PageControls = ({
  datePreset, setDatePreset,
  granularity, setGranularity,
  comparison, setComparison,
  viewBy, setViewBy,
  reportType, onReset,
  showGranularity = false, // RC-PAGE-012 — granularity now lives in the chart section, not the page top bar
  showViewBy = true,
}) => {
  const [dateOpen, setDateOpen] = React.useState(false);
  const [viewByOpen, setViewByOpen] = React.useState(false);
  const [compareOpen, setCompareOpen] = React.useState(false);

  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '10px 24px', background: 'var(--rc-subtle)',
      borderBottom: '1px solid var(--rc-border)', gap: 12, flexWrap: 'wrap',
    }}>
      {/* Left cluster — date + granularity */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
        {/* Date preset */}
        <div style={{ position: 'relative' }}>
          <button onClick={() => { setDateOpen(!dateOpen); setViewByOpen(false); setCompareOpen(false); }} style={dropdownBtn}>
            <Icon name="calendar" size={13} />
            {DATE_PRESETS.find(p => p.value === datePreset)?.label}
            <Icon name="chevronDown" size={10} />
          </button>
          {dateOpen && (
            <Dropdown onClose={() => setDateOpen(false)}>
              {DATE_PRESETS.map(p => (
                <DropItem key={p.value} active={p.value === datePreset} onClick={() => { setDatePreset(p.value); setDateOpen(false); }}>
                  {p.label}
                </DropItem>
              ))}
            </Dropdown>
          )}
        </div>
        <span style={{ fontSize: 11, color: 'var(--rc-text-sub)', fontVariantNumeric: 'tabular-nums' }}>
          {DATE_RANGES[datePreset]}
        </span>

        {showGranularity && (
          <>
            <div style={{ width: 1, height: 18, background: 'var(--rc-border)', margin: '0 2px' }} />
            <Segmented
              tabs={[{ value: 'day', label: 'Day' }, { value: 'week', label: 'Week' }, { value: 'month', label: 'Month' }]}
              active={granularity} onChange={setGranularity} size="sm" />
          </>
        )}
      </div>

      {/* Right cluster */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        {showViewBy && (
          <div style={{ position: 'relative' }}>
            <button onClick={() => { setViewByOpen(!viewByOpen); setDateOpen(false); setCompareOpen(false); }} style={dropdownBtn}>
              <Icon name="grid" size={12} />
              View By: {viewBy.join(' › ')}
              <Icon name="chevronDown" size={10} />
            </button>
            {viewByOpen && (
              <ViewByPicker
                options={reportType.viewByDims}
                selected={viewBy}
                onChange={setViewBy}
                onClose={() => setViewByOpen(false)}
              />
            )}
          </div>
        )}
        <div style={{ position: 'relative' }}>
          <button onClick={() => { setCompareOpen(!compareOpen); setDateOpen(false); setViewByOpen(false); }} style={dropdownBtn}>
            <Icon name="chart" size={12} />
            Compare: {comparison === 'py' ? 'Prior Year' : comparison === 'pp' ? 'Prior Period' : 'None'}
            <Icon name="chevronDown" size={10} />
          </button>
          {compareOpen && (
            <Dropdown onClose={() => setCompareOpen(false)}>
              <DropItem active={comparison === 'none'} onClick={() => { setComparison('none'); setCompareOpen(false); }}>None</DropItem>
              <DropItem active={comparison === 'pp'} onClick={() => { setComparison('pp'); setCompareOpen(false); }}>Prior Period</DropItem>
              <DropItem active={comparison === 'py'} onClick={() => { setComparison('py'); setCompareOpen(false); }}>Prior Year</DropItem>
            </Dropdown>
          )}
        </div>
        <Btn icon="reset" variant="ghost" size="sm" onClick={onReset}>Reset</Btn>
      </div>
    </div>
  );
};

const dropdownBtn = {
  display: 'inline-flex', alignItems: 'center', gap: 6,
  padding: '6px 10px', background: 'var(--rc-card)',
  border: '1px solid var(--rc-border)', borderRadius: 7,
  fontSize: 12, fontWeight: 500, color: 'var(--rc-text)', cursor: 'pointer',
  fontFamily: 'inherit', whiteSpace: 'nowrap',
};

const Dropdown = ({ children, onClose, align = 'left', width = 180 }) => (
  <>
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
    <div style={{
      position: 'absolute', top: 'calc(100% + 4px)', [align]: 0, zIndex: 41,
      background: 'var(--rc-card)', border: '1px solid var(--rc-border)',
      borderRadius: 8, boxShadow: '0 10px 30px -8px rgba(15,23,42,0.18)',
      minWidth: width, padding: 4,
    }}>{children}</div>
  </>
);

const DropItem = ({ active, onClick, children, hint }) => (
  <button onClick={onClick} style={{
    display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%',
    padding: '7px 10px', background: active ? 'var(--rc-hover)' : 'transparent',
    border: 0, borderRadius: 5, textAlign: 'left',
    color: 'var(--rc-text)', fontSize: 12, fontFamily: 'inherit',
    cursor: 'pointer', fontWeight: active ? 500 : 400,
  }}>
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
      {active && <Icon name="check" size={11} color="var(--rc-green-ink)" strokeWidth={2.5} />}
      {!active && <span style={{ width: 11 }} />}
      {children}
    </span>
    {hint && <span style={{ color: 'var(--rc-text-mute)', fontSize: 11 }}>{hint}</span>}
  </button>
);

/* RC-PAGE-030 — multi-dimension ordered View By picker. Stacked chips w/ drag-reorder.
   RC-PAGE-031 — pivot resolver badges + strategy summary. */
const ViewByPicker = ({ options, selected, onChange, onClose, disabled = false }) => {
  const [dragIdx, setDragIdx] = React.useState(null);
  const [hoverIdx, setHoverIdx] = React.useState(null);
  const plan = (window.resolvePivot || (() => ({ strategy: 'empty', chips: [], warnings: [] })))(selected);

  const toggle = (dim) => {
    if (disabled) return;
    if (selected.includes(dim)) onChange(selected.filter(d => d !== dim));
    else onChange([...selected, dim]);
  };
  const reorder = (from, to) => {
    if (from === to || from == null || to == null) return;
    const next = [...selected];
    const [moved] = next.splice(from, 1);
    next.splice(to, 0, moved);
    onChange(next);
  };
  return (
    <>
      <div onClick={onClose} 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)',
        width: 300, padding: 10,
      }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', padding: '2px 4px 8px' }}>
          <span style={{ fontSize: 11, color: 'var(--rc-text-sub)', fontWeight: 500 }}>
            Nest in order — drag to reorder
          </span>
          {disabled && (
            <span style={{ fontSize: 10, color: 'var(--rc-text-mute)', fontStyle: 'italic' }}>View-only</span>
          )}
        </div>
        {/* Selected (ordered) */}
        {selected.length > 0 && (
          <div style={{ marginBottom: 8, display: 'flex', flexDirection: 'column', gap: 3 }}>
            {selected.map((dim, i) => {
              const isDragging = dragIdx === i;
              const isTarget = hoverIdx === i && dragIdx != null && dragIdx !== i;
              const insertAbove = isTarget && dragIdx > i;
              const insertBelow = isTarget && dragIdx < i;
              return (
                <div key={dim}
                  draggable={!disabled}
                  onDragStart={(e) => { setDragIdx(i); e.dataTransfer.effectAllowed = 'move'; }}
                  onDragOver={(e) => { e.preventDefault(); setHoverIdx(i); }}
                  onDragLeave={() => { if (hoverIdx === i) setHoverIdx(null); }}
                  onDrop={(e) => { e.preventDefault(); reorder(dragIdx, i); setDragIdx(null); setHoverIdx(null); }}
                  onDragEnd={() => { setDragIdx(null); setHoverIdx(null); }}
                  style={{
                    position: 'relative',
                    display: 'flex', alignItems: 'center', gap: 6,
                    padding: '6px 8px',
                    background: isTarget ? 'color-mix(in srgb, var(--rc-green) 18%, transparent)'
                      : 'color-mix(in srgb, var(--rc-green) 8%, transparent)',
                    border: `1px ${isTarget ? 'dashed' : 'solid'} color-mix(in srgb, var(--rc-green) ${isTarget ? '45%' : '25%'}, transparent)`,
                    borderRadius: 6, fontSize: 12, color: 'var(--rc-text)',
                    opacity: isDragging ? 0.35 : 1,
                    transform: isDragging ? 'scale(0.98)' : 'scale(1)',
                    cursor: disabled ? 'not-allowed' : 'grab',
                    transition: 'background 0.1s, border-color 0.1s, opacity 0.12s, transform 0.12s',
                  }}>
                  {insertAbove && (
                    <div style={{
                      position: 'absolute', left: 2, right: 2, top: -2, height: 3,
                      background: 'var(--rc-green)', borderRadius: 2, zIndex: 2,
                    }} />
                  )}
                  {insertBelow && (
                    <div style={{
                      position: 'absolute', left: 2, right: 2, bottom: -2, height: 3,
                      background: 'var(--rc-green)', borderRadius: 2, zIndex: 2,
                    }} />
                  )}
                  <Icon name="drag" size={12} color="var(--rc-text-mute)" />
                  <span style={{
                    width: 16, height: 16, borderRadius: 9999, fontSize: 10, fontWeight: 600,
                    background: 'var(--rc-green)', color: '#fff',
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    fontVariantNumeric: 'tabular-nums',
                  }}>{i + 1}</span>
                  {plan.chips[i] && (() => {
                    const ch = plan.chips[i];
                    const st = (window.RELATION_STYLES || {})[ch.relation] || { glyph: '·', tint: 'var(--rc-text-mute)', label: '' };
                    return (
                      <span title={ch.detail || ch.label}
                        style={{
                          display: 'inline-flex', alignItems: 'center', gap: 3,
                          padding: '1px 5px', borderRadius: 10,
                          fontSize: 9.5, fontWeight: 600, fontFamily: 'JetBrains Mono',
                          background: `color-mix(in srgb, ${st.tint} 14%, transparent)`,
                          color: st.tint,
                          letterSpacing: 0.2, lineHeight: 1,
                        }}>
                        <span style={{ fontSize: 11, lineHeight: 1 }}>{st.glyph}</span>
                        {st.label}
                      </span>
                    );
                  })()}
                  <span style={{ flex: 1 }}>{dim}</span>
                  {!disabled && <IconBtn name="x" title="Remove" size={20} onClick={() => toggle(dim)} />}
                </div>
              );
            })}
          </div>
        )}
        {/* Resolution summary (only when 2+ dims selected) */}
        {selected.length >= 2 && (
          <div style={{
            margin: '2px 2px 8px', padding: '6px 8px',
            background: 'var(--rc-subtle)', border: '1px solid var(--rc-border-soft)',
            borderRadius: 6, fontSize: 10.5, color: 'var(--rc-text-sub)',
            display: 'flex', flexDirection: 'column', gap: 4,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontWeight: 600, color: 'var(--rc-text)' }}>Resolution</span>
              <span style={{
                padding: '1px 6px', borderRadius: 9999,
                fontFamily: 'JetBrains Mono', fontSize: 9.5, letterSpacing: 0.3,
                textTransform: 'uppercase',
                background: plan.strategy === 'nested'
                  ? 'color-mix(in srgb, var(--rc-green) 14%, transparent)'
                  : plan.strategy === 'crosstab'
                    ? 'color-mix(in srgb, var(--rc-chart-2) 14%, transparent)'
                    : plan.strategy === 'mixed'
                      ? 'color-mix(in srgb, var(--rc-amber) 14%, transparent)'
                      : 'var(--rc-hover)',
                color: plan.strategy === 'nested' ? 'var(--rc-green)'
                  : plan.strategy === 'crosstab' ? 'var(--rc-chart-2)'
                  : plan.strategy === 'mixed' ? 'var(--rc-amber)'
                  : 'var(--rc-text-sub)',
              }}>{plan.strategy}</span>
            </div>
            <div style={{ fontSize: 10.5, lineHeight: 1.4 }}>
              {plan.strategy === 'nested' && 'Each row nests cleanly under its parent.'}
              {plan.strategy === 'crosstab' && 'Independent attributes — rendered as a crosstab of every combination.'}
              {plan.strategy === 'mixed' && 'Mixed relationships — some nest, some pivot. Review the chip order.'}
            </div>
            {plan.warnings.length > 0 && plan.warnings.map((w, wi) => (
              <div key={wi} style={{
                display: 'flex', alignItems: 'flex-start', gap: 5,
                padding: '4px 6px', marginTop: 2,
                background: 'color-mix(in srgb, var(--rc-amber) 10%, transparent)',
                border: '1px solid color-mix(in srgb, var(--rc-amber) 30%, transparent)',
                borderRadius: 5, color: 'var(--rc-amber)', fontSize: 10,
              }}>
                <Icon name="alert" size={10} color="var(--rc-amber)" />
                <span style={{ flex: 1, lineHeight: 1.35 }}>{w}</span>
              </div>
            ))}
          </div>
        )}
        <div style={{ fontSize: 11, color: 'var(--rc-text-sub)', fontWeight: 500, padding: '6px 4px 4px', borderTop: '1px solid var(--rc-border-soft)' }}>
          {selected.length === 0 ? 'Pick one or more dimensions' : '+ Add another dimension'}
        </div>
        {options.filter(d => !selected.includes(d)).map(dim => (
          <button key={dim} onClick={() => toggle(dim)}
            disabled={disabled}
            style={{
              display: 'flex', alignItems: 'center', width: '100%',
              padding: '7px 8px', background: 'transparent', border: 0, borderRadius: 5,
              textAlign: 'left', color: 'var(--rc-text)', fontSize: 12,
              cursor: disabled ? 'not-allowed' : 'pointer', fontFamily: 'inherit',
              opacity: disabled ? 0.5 : 1,
            }}
            onMouseEnter={e => { if (!disabled) e.currentTarget.style.background = 'var(--rc-hover)'; }}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            <Icon name="plus" size={11} color="var(--rc-text-mute)" />
            <span style={{ marginLeft: 8 }}>{dim}</span>
          </button>
        ))}
      </div>
    </>
  );
};

Object.assign(window, { PageControls, DATE_PRESETS, DATE_RANGES, Dropdown, DropItem, ViewByPicker });

/* ----- Compact per-section controls (used inside each PageSection header) ----- */
const SectionControls = ({
  datePreset, setDatePreset,
  granularity, setGranularity,
  comparison, setComparison,
  viewBy, setViewBy, reportType,
  showGranularity = false,
  onCustomDate,
  customDateLabel,
  viewerDisabled = false,
}) => {
  const dBtn = viewerDisabled ? { ...sectionBtn, cursor: 'default', opacity: 0.55 } : sectionBtn;
  const [dateOpen, setDateOpen] = React.useState(false);
  const [cmpOpen, setCmpOpen] = React.useState(false);
  const [vbOpen, setVbOpen] = React.useState(false);

  /* RC-PAGE-013 — canonical 16-range math: resolve real current + comparison ranges */
  const cur = React.useMemo(() => {
    if (datePreset === 'custom') return null;
    return window.presetRange ? window.presetRange(datePreset) : null;
  }, [datePreset]);
  const cmp = React.useMemo(() => {
    if (!cur || comparison === 'none') return null;
    return window.comparisonRange ? window.comparisonRange(datePreset, comparison) : null;
  }, [datePreset, comparison, cur]);
  const curLabel = cur ? window.fmtRangeLabel(cur.start, cur.end) : (customDateLabel || '—');
  const cmpLabel = cmp ? window.fmtRangeLabel(cmp.start, cmp.end) : null;

  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
      {/* Date */}
      <div style={{ position: 'relative' }}>
        <button onClick={() => { if (viewerDisabled) return; setDateOpen(!dateOpen); setCmpOpen(false); setVbOpen(false); }}
          style={{ ...dBtn, padding: '4px 9px', flexDirection: 'column', alignItems: 'flex-start', gap: 1 }}
          title={viewerDisabled ? 'View-only — date range locked' : (cmpLabel ? `vs ${cmpLabel}` : undefined)}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
            <Icon name="calendar" size={11} />
            <span style={{ fontWeight: 600 }}>
              {DATE_PRESETS.find(p => p.value === datePreset)?.label
                .replace('Month-to-Date', 'MTD')
                .replace('Year-to-Date', 'YTD')
                .replace('Week-to-Date', 'WTD')}
            </span>
            <span style={{ color: 'var(--rc-text-sub)', fontWeight: 400, fontVariantNumeric: 'tabular-nums' }}>
              · {datePreset === 'custom' && customDateLabel ? customDateLabel : curLabel}
            </span>
            <Icon name="chevronDown" size={9} />
          </span>
        </button>
        {dateOpen && (
          <Dropdown onClose={() => setDateOpen(false)} align="right">
            {DATE_PRESETS.map(p => (
              <DropItem key={p.value} active={p.value === datePreset}
                onClick={() => {
                  setDateOpen(false);
                  if (p.value === 'custom' && onCustomDate) {
                    onCustomDate();
                  } else {
                    setDatePreset(p.value);
                  }
                }}>
                {p.label}
              </DropItem>
            ))}
          </Dropdown>
        )}
      </div>

      {/* Granularity */}
      {showGranularity && setGranularity && (
        <Segmented
          tabs={[{ value: 'day', label: 'D' }, { value: 'week', label: 'W' }, { value: 'month', label: 'M' }]}
          active={granularity} onChange={setGranularity} size="sm" />
      )}

      {/* View By — stacked chips inline summary */}
      {viewBy && setViewBy && reportType && (
        <div style={{ position: 'relative' }}>
          <button onClick={() => { if (viewerDisabled) return; setVbOpen(!vbOpen); setDateOpen(false); setCmpOpen(false); }}
            style={{ ...dBtn, padding: '3px 8px 3px 6px', gap: 4 }}
            title={viewerDisabled ? 'View-only — dimensions locked' : 'View By — drag to reorder'}>
            <Icon name="grid" size={11} />
            <span style={{ color: 'var(--rc-text-sub)', fontWeight: 500 }}>View:</span>
            {viewBy.slice(0, 3).map((dim, i) => (
              <React.Fragment key={dim}>
                {i > 0 && <Icon name="chevronRight" size={9} color="var(--rc-text-mute)" />}
                <span style={{
                  display: 'inline-flex', alignItems: 'center',
                  padding: '2px 7px', borderRadius: 9999,
                  background: 'color-mix(in srgb, var(--rc-green) 12%, transparent)',
                  color: 'var(--rc-green-ink)',
                  fontSize: 10, fontWeight: 600,
                }}>{dim}</span>
              </React.Fragment>
            ))}
            {viewBy.length > 3 && (
              <span style={{ fontSize: 10, color: 'var(--rc-text-sub)' }}>+{viewBy.length - 3}</span>
            )}
            <Icon name="chevronDown" size={9} />
          </button>
          {vbOpen && (
            <ViewByPicker
              options={reportType.viewByDims}
              selected={viewBy}
              onChange={setViewBy}
              onClose={() => setVbOpen(false)}
              disabled={viewerDisabled}
            />
          )}
        </div>
      )}

      {/* Compare */}
      <div style={{ position: 'relative' }}>
        <button onClick={() => { if (viewerDisabled) return; setCmpOpen(!cmpOpen); setDateOpen(false); setVbOpen(false); }} style={dBtn}
          title={viewerDisabled ? 'View-only — comparison locked' : (cmpLabel ? cmpLabel : undefined)}>
          <Icon name="chart" size={11} />
          vs {comparison === 'py' ? 'Prior Year' : comparison === 'pp' ? 'Prior Period' : 'None'}
          {cmpLabel && (
            <span style={{ color: 'var(--rc-text-sub)', fontWeight: 400, marginLeft: 4, fontVariantNumeric: 'tabular-nums' }}>
              · {cmpLabel}
            </span>
          )}
          <Icon name="chevronDown" size={9} />
        </button>
        {cmpOpen && (
          <Dropdown onClose={() => setCmpOpen(false)} align="right">
            <DropItem active={comparison === 'none'} onClick={() => { setComparison('none'); setCmpOpen(false); }}>None</DropItem>
            <DropItem active={comparison === 'pp'} onClick={() => { setComparison('pp'); setCmpOpen(false); }}>Prior Period</DropItem>
            <DropItem active={comparison === 'py'} onClick={() => { setComparison('py'); setCmpOpen(false); }}>Prior Year</DropItem>
          </Dropdown>
        )}
      </div>
    </div>
  );
};

const sectionBtn = {
  display: 'inline-flex', alignItems: 'center', gap: 5,
  padding: '4px 8px', background: 'var(--rc-card)',
  border: '1px solid var(--rc-border)', borderRadius: 6,
  fontSize: 11, fontWeight: 500, color: 'var(--rc-text)', cursor: 'pointer',
  fontFamily: 'inherit', whiteSpace: 'nowrap',
};

Object.assign(window, { SectionControls });
