/* PageSection — stacks each page as its own card with header + local controls.
   New layout: all 4 pages render in one scrollable column, each a discrete section. */

/* RC-PAGE-024 — infer paste-list dimension from section id.
   Page 1 (time-series chart) and Page 2 (range scorecards) have no row-level
   entities to filter, so Filter becomes a light hint instead of a paste-list hook. */
const SECTION_FILTER_DIM = {
  'rc-page-time':      null,           // chart — no list filter
  'rc-page-range':     null,           // scorecards — no list filter
  'rc-page-metric':    'ASIN',         // item-breakdown table
  'rc-page-dimension': 'Campaign ID',  // by-dimension table
};

const PageSection = ({ id, title, report, children, compactControls, onCustomize, customizeLabel, collapsed: collapsedProp, onToggleCollapsed, canEdit = true, state = 'ready', skeletonKind = 'chart', onRetry, errorMsg, sectionConfig }) => {
  const [localCollapsed, setLocalCollapsed] = React.useState(false);
  const collapsed = collapsedProp != null ? collapsedProp : localCollapsed;
  const toggle = () => {
    if (onToggleCollapsed) onToggleCollapsed();
    else setLocalCollapsed(!localCollapsed);
  };

  // RC-PAGE-024 — paste-list filter state (per-section, ephemeral; real impl would live in URL/session store)
  const [pasteOpen, setPasteOpen] = React.useState(false);
  const [pasteFilter, setPasteFilter] = React.useState(null); // { values:[], mode:'include'|'exclude' }
  const dimLabel = SECTION_FILTER_DIM[id];
  const hasPasteSupport = !!dimLabel;

  /* RC-RPT-060 — per-section default config (compound key: reportId × sectionId × userId).
     Stub key: rc2_section_default__<reportId>__<sectionId> in localStorage.
     Saves the current `sectionConfig` (passed in from parent) as this user's default
     for this section of this report. Real impl goes through reports.defaults. */
  const sectionDefaultKey = `rc2_section_default__${report?.id || 'default'}__${id}`;
  const [sectionDefault, setSectionDefault] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem(sectionDefaultKey) || 'null'); }
    catch (e) { return null; }
  });
  const hasSectionDefault = !!sectionDefault;

  // More-menu state
  const [menuOpen, setMenuOpen] = React.useState(false);
  const menuRef = React.useRef(null);
  React.useEffect(() => {
    if (!menuOpen) return;
    const h = (e) => { if (menuRef.current && !menuRef.current.contains(e.target)) setMenuOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [menuOpen]);

  const saveAsDefault = () => {
    const payload = {
      savedAt: new Date().toISOString(),
      savedBy: 'you@mixshift.io',
      config: sectionConfig || {},
    };
    try {
      localStorage.setItem(sectionDefaultKey, JSON.stringify(payload));
      setSectionDefault(payload);
      window.__rcToast && window.__rcToast.push && window.__rcToast.push({
        kind: 'success',
        title: 'Section default saved',
        detail: `“${title}” will open with this configuration next time.`,
        timeout: 3500,
      });
    } catch (e) {
      window.__rcToast && window.__rcToast.push && window.__rcToast.push({
        kind: 'error',
        title: 'Couldn\'t save default',
        detail: 'Storage unavailable. Try again.',
        timeout: 4000,
      });
    }
    setMenuOpen(false);
  };
  const clearDefault = () => {
    try { localStorage.removeItem(sectionDefaultKey); } catch (e) {}
    setSectionDefault(null);
    window.__rcToast && window.__rcToast.push && window.__rcToast.push({
      kind: 'info',
      title: 'Section default cleared',
      detail: `“${title}” is back to the report's baseline.`,
      timeout: 3000,
    });
    setMenuOpen(false);
  };
  return (
    <section id={id} data-screen-label={title}
      style={{
        background: 'var(--rc-card)',
        border: '1px solid var(--rc-border)',
        borderRadius: 12,
        overflow: 'hidden',
        boxShadow: '0 1px 2px rgba(15,23,42,0.04)',
        scrollMarginTop: 12,
      }}>
      {/* Section header */}
      <div style={{
        padding: '10px 16px',
        borderBottom: collapsed ? 'none' : '1px solid var(--rc-border)',
        background: 'var(--rc-card)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 12, flexWrap: 'wrap',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <button onClick={toggle} title={collapsed ? 'Expand section' : 'Collapse section'}
            style={{
              width: 24, height: 24, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              border: '1px solid var(--rc-border)', borderRadius: 6,
              background: 'var(--rc-card)', color: 'var(--rc-text-sub)',
              cursor: 'pointer', fontFamily: 'inherit', padding: 0,
            }}>
            <Icon name={collapsed ? 'chevronRight' : 'chevronDown'} size={12} />
          </button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
            <h2 style={{
              margin: 0, fontFamily: 'Poppins', fontSize: 14, fontWeight: 700,
              color: 'var(--rc-text)', letterSpacing: '-0.01em',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{report.name} <span style={{ color: 'var(--rc-text-mute)', fontWeight: 500 }}>/ {title}</span></h2>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          {compactControls}
          {onCustomize && canEdit && (
            <button onClick={onCustomize} title={customizeLabel || 'Customize'}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                padding: '4px 9px', border: '1px solid var(--rc-border)', borderRadius: 6,
                background: 'var(--rc-card)', color: 'var(--rc-text)',
                fontSize: 11, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
              }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--rc-hover)'}
              onMouseLeave={e => e.currentTarget.style.background = 'var(--rc-card)'}>
              <Icon name="settings" size={11} />
              {customizeLabel || 'Customize'}
            </button>
          )}
          {/* RC-PAGE-024 — active paste-filter chip (only when applied) */}
          {pasteFilter && pasteFilter.values.length > 0 && (
            <span
              title={`${pasteFilter.mode === 'include' ? 'Including' : 'Excluding'} ${pasteFilter.values.length} ${dimLabel}${pasteFilter.values.length === 1 ? '' : 's'}`}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                padding: '3px 4px 3px 9px', border: '1px solid var(--rc-green)',
                borderRadius: 6, fontSize: 11, fontWeight: 500,
                background: 'color-mix(in srgb, var(--rc-green) 10%, var(--rc-card))',
                color: 'var(--rc-green-ink)', fontFamily: 'inherit',
              }}>
              <Icon name="filter" size={10} />
              {pasteFilter.mode === 'include' ? '' : 'Not '}
              {pasteFilter.values.length} {dimLabel}{pasteFilter.values.length === 1 ? '' : 's'}
              <button
                onClick={() => setPasteFilter(null)}
                title="Clear list filter"
                style={{
                  width: 16, height: 16, padding: 0, border: 0, borderRadius: 4,
                  background: 'transparent', color: 'var(--rc-green-ink)',
                  cursor: 'pointer', display: 'inline-flex',
                  alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'inherit',
                }}
                onMouseEnter={e => e.currentTarget.style.background = 'color-mix(in srgb, var(--rc-green) 20%, transparent)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
              >
                <Icon name="x" size={10} />
              </button>
            </span>
          )}
          <button
            title={hasPasteSupport
              ? `Filter by ${dimLabel} — paste list`
              : 'List filtering applies to item/campaign sections'}
            disabled={!hasPasteSupport}
            onClick={() => { if (hasPasteSupport) setPasteOpen(true); }}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              padding: '4px 9px', border: '1px solid var(--rc-border)', borderRadius: 6,
              background: 'var(--rc-card)',
              color: hasPasteSupport ? 'var(--rc-text-sub)' : 'var(--rc-text-mute)',
              fontSize: 11, fontWeight: 500,
              cursor: hasPasteSupport ? 'pointer' : 'not-allowed',
              opacity: hasPasteSupport ? 1 : 0.6,
              fontFamily: 'inherit',
            }}
            onMouseEnter={e => { if (hasPasteSupport) e.currentTarget.style.background = 'var(--rc-hover)'; }}
            onMouseLeave={e => { e.currentTarget.style.background = 'var(--rc-card)'; }}>
            <Icon name="filter" size={11} />
            {hasPasteSupport ? 'Paste list' : 'Filter'}
          </button>
          {/* Paste-list modal (lazy — only when supported) */}
          {hasPasteSupport && window.ListPasteFilterModal && (
            <window.ListPasteFilterModal
              open={pasteOpen}
              onClose={() => setPasteOpen(false)}
              dimensionLabel={dimLabel}
              onApply={(res) => {
                setPasteFilter(res);
                window.__rcToast && window.__rcToast.push && window.__rcToast.push({
                  kind: 'success',
                  title: 'List filter applied',
                  detail: `${res.mode === 'include' ? 'Including' : 'Excluding'} ${res.values.length} ${dimLabel}${res.values.length === 1 ? '' : 's'} in ${title}`,
                  timeout: 3500,
                });
              }}
            />
          )}
          <IconBtn name="download" title="Export section"
            onClick={() => {
              const sid = window.__rcToast.exportStarted({ scope: title });
              // Simulate backend call — ~55% success, ~45% fail
              setTimeout(() => {
                window.__rcToast.dismiss(sid);
                if (Math.random() < 0.55) {
                  window.__rcToast.exportSucceeded({
                    scope: title,
                    filename: `${(report?.name || 'report').toLowerCase().replace(/\s+/g, '-')}_${title.toLowerCase().replace(/\s+/g, '-')}.xlsx`,
                  });
                } else {
                  window.__rcToast.exportFailed({
                    scope: title,
                    onRetry: () => {
                      // Retry path — always succeeds
                      const sid2 = window.__rcToast.exportStarted({ scope: title });
                      setTimeout(() => {
                        window.__rcToast.dismiss(sid2);
                        window.__rcToast.exportSucceeded({
                          scope: title,
                          filename: `${(report?.name || 'report').toLowerCase().replace(/\s+/g, '-')}_${title.toLowerCase().replace(/\s+/g, '-')}.xlsx`,
                        });
                      }, 1200);
                    },
                  });
                }
              }, 1100);
            }} />
          <div ref={menuRef} style={{ position: 'relative' }}>
            <IconBtn name="moreH" title="More" onClick={() => setMenuOpen(!menuOpen)} active={menuOpen} />
            {/* RC-RPT-060 — saved-default indicator dot */}
            {hasSectionDefault && (
              <span
                title={`Section default saved ${new Date(sectionDefault.savedAt).toLocaleDateString()}`}
                style={{
                  position: 'absolute', top: 2, right: 2,
                  width: 6, height: 6, borderRadius: '50%',
                  background: 'var(--rc-green)',
                  border: '1.5px solid var(--rc-card)',
                  pointerEvents: 'none',
                }} />
            )}
            {menuOpen && (
              <div style={{
                position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 40,
                minWidth: 240,
                background: 'var(--rc-card)', border: '1px solid var(--rc-border)',
                borderRadius: 8, boxShadow: '0 14px 32px -6px rgba(15,23,42,0.22)',
                padding: 6, display: 'flex', flexDirection: 'column', gap: 1,
                fontFamily: 'Inter',
              }}>
                <div style={{
                  padding: '6px 10px 4px', fontSize: 10, fontWeight: 600,
                  color: 'var(--rc-text-mute)', fontFamily: 'JetBrains Mono, monospace',
                  letterSpacing: '0.05em',
                }}>
                  SECTION DEFAULTS · RC-RPT-060
                </div>
                {canEdit ? (
                  <>
                    <button onClick={saveAsDefault} style={menuItemStyle}
                      onMouseEnter={e => e.currentTarget.style.background = 'var(--rc-hover)'}
                      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                      <Icon name="bookmark" size={12} color="var(--rc-text-sub)" />
                      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 1 }}>
                        <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--rc-text)' }}>
                          {hasSectionDefault ? 'Update default' : 'Save as default'}
                        </span>
                        <span style={{ fontSize: 10, color: 'var(--rc-text-mute)' }}>
                          Use this config whenever the section opens
                        </span>
                      </div>
                    </button>
                    {/* Preview of what will be saved — collapsed by default */}
                    {sectionConfig && Object.keys(sectionConfig).length > 0 && (
                      <details style={{ margin: '0 4px 2px' }}>
                        <summary style={{
                          padding: '4px 8px', fontSize: 10,
                          color: 'var(--rc-text-mute)',
                          fontFamily: 'JetBrains Mono, monospace',
                          cursor: 'pointer', userSelect: 'none',
                          display: 'flex', alignItems: 'center', gap: 4,
                        }}>
                          <Icon name="chevronRight" size={10} />
                          Preview what gets saved
                        </summary>
                        <div style={{
                          marginTop: 4, padding: '6px 8px',
                          background: 'color-mix(in srgb, var(--rc-chart-1) 4%, var(--rc-card))',
                          border: '1px solid var(--rc-border-soft, var(--rc-border))',
                          borderRadius: 6,
                          display: 'flex', flexDirection: 'column', gap: 3,
                          fontSize: 10, fontFamily: 'JetBrains Mono, monospace',
                          maxHeight: 140, overflow: 'auto',
                        }}>
                          {Object.entries(sectionConfig).slice(0, 8).map(([k, v]) => {
                            const savedV = hasSectionDefault ? sectionDefault.config?.[k] : undefined;
                            const fmt = (val) => Array.isArray(val)
                              ? `[${val.length}]`
                              : typeof val === 'object' && val !== null ? JSON.stringify(val).slice(0, 30)
                              : String(val ?? '—');
                            const asKey = (val) => Array.isArray(val) ? val.join(',') : JSON.stringify(val);
                            const changed = hasSectionDefault && asKey(v) !== asKey(savedV);
                            return (
                              <div key={k} style={{
                                display: 'flex', justifyContent: 'space-between', gap: 6,
                                color: changed ? 'var(--rc-text)' : 'var(--rc-text-sub)',
                              }}>
                                <span style={{ fontWeight: changed ? 600 : 400 }}>
                                  {changed && '•'} {k}
                                </span>
                                <span style={{
                                  color: changed ? 'var(--rc-green)' : 'var(--rc-text-mute)',
                                  overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                                  maxWidth: 140,
                                }}>{fmt(v)}</span>
                              </div>
                            );
                          })}
                          {Object.keys(sectionConfig).length > 8 && (
                            <div style={{ color: 'var(--rc-text-mute)' }}>
                              +{Object.keys(sectionConfig).length - 8} more key{Object.keys(sectionConfig).length - 8 === 1 ? '' : 's'}
                            </div>
                          )}
                        </div>
                      </details>
                    )}
                  </>
                ) : (
                  <div style={{
                    padding: '8px 10px', fontSize: 11,
                    color: 'var(--rc-text-mute)', fontStyle: 'italic',
                  }}>
                    Viewers can't change defaults.
                  </div>
                )}
                {hasSectionDefault && canEdit && (
                  <button onClick={clearDefault} style={menuItemStyle}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--rc-hover)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                    <Icon name="x" size={12} color="var(--rc-red, #dc2626)" />
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 1 }}>
                      <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--rc-text)' }}>
                        Clear saved default
                      </span>
                      <span style={{ fontSize: 10, color: 'var(--rc-text-mute)', fontFamily: 'JetBrains Mono, monospace' }}>
                        Saved {new Date(sectionDefault.savedAt).toLocaleDateString()}
                      </span>
                    </div>
                  </button>
                )}
                <div style={{ height: 1, background: 'var(--rc-border)', margin: '4px 0' }} />
                <button
                  onClick={() => { setMenuOpen(false); if (onToggleCollapsed) onToggleCollapsed(); else setLocalCollapsed(true); }}
                  onMouseEnter={e => e.currentTarget.style.background = 'var(--rc-hover)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                  style={menuItemStyle}>
                  <Icon name="chevronDown" size={12} color="var(--rc-text-sub)" />
                  <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--rc-text)' }}>Collapse section</span>
                </button>
                <button
                  onClick={() => {
                    setMenuOpen(false);
                    const url = `${window.location.pathname}${window.location.search}#${id}`;
                    navigator.clipboard && navigator.clipboard.writeText(window.location.origin + url);
                    window.__rcToast && window.__rcToast.push && window.__rcToast.push({
                      kind: 'success', title: 'Link copied',
                      detail: `Deep link to ${title}`,
                      timeout: 2500,
                    });
                  }}
                  onMouseEnter={e => e.currentTarget.style.background = 'var(--rc-hover)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                  style={menuItemStyle}>
                  <Icon name="link" size={12} color="var(--rc-text-sub)" />
                  <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--rc-text)' }}>Copy link to section</span>
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
      {!collapsed && (
        <div>
          {state === 'loading' && <SectionSkeleton kind={skeletonKind} />}
          {state === 'error' && <SectionError msg={errorMsg || 'Could not load this section.'} detail="Upstream data source timed out. Try again in a moment." onRetry={onRetry} />}
          {state === 'ready' && children}
        </div>
      )}
    </section>
  );
};

Object.assign(window, { PageSection });

/* Local style — hoisted so JSX can reference it. */
const menuItemStyle = {
  display: 'flex', alignItems: 'center', gap: 8,
  padding: '7px 10px', width: '100%',
  background: 'transparent', border: 0, borderRadius: 6,
  cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit',
};
/* Hover handled inline via onMouseEnter/Leave where needed; keep rows subtle. */
