// Shared building blocks for all tool pages.
// Anatomy every tool follows:
//   ToolPageHeader  — page eyebrow + title + one-line scope statement
//   ToolFrame       — two-column shell (inputs left, result right); stacks on mobile at <900px
//   InputCard       — paper card wrapping an input group
//   NumberField     — labeled numeric input with hint line
//   MoneyField      — like NumberField but formats value with commas
//   SplitField      — slider that splits 100% between two named sides
//   ResultPanel     — right-hand result: big headline number + breakdown rows + footnote
//   ToolFooter      — "what this doesn't measure" + soft CTA + related insight link
//   ToolReference   — "the terms, briefly" + "why you should care" (optional, above ToolFooter)
//
// All components export to window.* so they are available to downstream tool scripts
// loaded as separate <script type="text/babel"> tags (no ES module bundler).
//
// Production port notes:
//   - "← All tools" links updated from "Pareto Tools.html" to "/Tools"
//   - SiteNav / SiteFooter are NOT here — handled by _Layout.cshtml
//   - mock-auth.js and mock-powerbi.js are NOT loaded — production uses real Azure AD + PowerBI

const { useState: tUseState, useMemo: tUseMemo } = React;

// --- helpers ---
const fmtMoney = (n) => {
  if (!isFinite(n)) return '—';
  if (Math.abs(n) >= 1e6) return '$' + (n / 1e6).toFixed(2) + 'M';
  if (Math.abs(n) >= 1e3) return '$' + Math.round(n / 1000).toLocaleString() + 'K';
  return '$' + Math.round(n).toLocaleString();
};

const fmtMoneyFull = (n) => {
  if (!isFinite(n)) return '—';
  return '$' + Math.round(n).toLocaleString();
};

const fmtPct = (n) => {
  if (!isFinite(n)) return '—';
  return (n * 100).toFixed(1) + '%';
};

// --- ToolPageHeader ---
// Used at the top of every tool page (below the site nav). Title + one-line scope.
function ToolPageHeader({ eyebrow, title, scope }) {
  return (
    <header style={{
      padding: 'clamp(48px, 8vw, 88px) clamp(16px, 4vw, 32px) clamp(28px, 4vw, 40px)',
      maxWidth: 1280, margin: '0 auto',
      borderBottom: '1px solid var(--pdt-line)',
    }}>
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 18, flexWrap: 'wrap',
        marginBottom: 28,
      }}>
        <a href="/Tools" className="t-eyebrow" style={{
          color: 'var(--pdt-mute)',
          textDecoration: 'none',
          borderBottom: '1px solid var(--pdt-line)',
          paddingBottom: 2,
        }}>
          ← All tools
        </a>
        {eyebrow && (
          <div className="t-eyebrow" style={{ color: 'var(--pdt-forest)' }}>
            {eyebrow}
          </div>
        )}
      </div>
      <h1 style={{
        fontSize: 'clamp(36px, 6vw, 68px)',
        margin: '0 0 20px',
        letterSpacing: '-0.02em', fontWeight: 500,
        lineHeight: 1.1, maxWidth: 900,
      }}>
        {title}
      </h1>
      <p className="t-lead" style={{ margin: 0, maxWidth: 680 }}>
        {scope}
      </p>
    </header>
  );
}

// --- ToolFrame ---
// Two-column shell: inputs on the left, result on the right. Stacks at <900px via .tool-grid.
function ToolFrame({ children }) {
  return (
    <section style={{
      padding: 'clamp(32px, 5vw, 56px) clamp(16px, 4vw, 32px)',
      maxWidth: 1280, margin: '0 auto',
    }}>
      <div className="tool-grid" style={{
        display: 'grid',
        gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.1fr)',
        gap: 'clamp(24px, 4vw, 56px)',
        alignItems: 'start',
      }}>
        {children}
      </div>
    </section>
  );
}

// --- InputCard ---
// Wraps the inputs panel in a paper card with a monospace section header.
function InputCard({ title, children }) {
  return (
    <div style={{
      background: 'var(--pdt-paper)',
      border: '1px solid var(--pdt-line)',
      padding: 'clamp(24px, 3.5vw, 36px)',
    }}>
      <div className="t-eyebrow" style={{
        marginBottom: 24,
        color: 'var(--pdt-mute)',
      }}>
        {title}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
        {children}
      </div>
    </div>
  );
}

// --- NumberField ---
// Labeled numeric input with an optional hint line. Empty value treated as the default.
function NumberField({ label, hint, value, onChange, min, max, step = 1, suffix, prefix }) {
  return (
    <label style={{ display: 'block' }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        marginBottom: 8, gap: 12,
      }}>
        <span style={{
          fontFamily: 'var(--pdt-mono)', fontSize: 11,
          letterSpacing: '0.08em', textTransform: 'uppercase',
          color: 'var(--pdt-ink)',
        }}>
          {label}
        </span>
        {hint && (
          <span style={{
            fontFamily: 'var(--pdt-mono)', fontSize: 10,
            color: 'var(--pdt-mute)', textAlign: 'right',
          }}>
            {hint}
          </span>
        )}
      </div>
      <div style={{
        display: 'flex', alignItems: 'stretch',
        border: '1px solid var(--pdt-line)',
        background: '#fff',
      }}>
        {prefix && (
          <span style={{
            padding: '12px 14px', borderRight: '1px solid var(--pdt-line-soft)',
            fontFamily: 'var(--pdt-mono)', fontSize: 13,
            color: 'var(--pdt-mute)', background: 'var(--pdt-paper-deep)',
            display: 'flex', alignItems: 'center',
          }}>
            {prefix}
          </span>
        )}
        <input
          type="number"
          value={value}
          min={min}
          max={max}
          step={step}
          onChange={(e) => {
            const v = e.target.value;
            onChange(v === '' ? '' : Number(v));
          }}
          style={{
            flex: 1, minWidth: 0,
            padding: '12px 14px',
            border: 'none', background: 'transparent',
            fontFamily: 'var(--pdt-sans)', fontSize: 18,
            fontWeight: 500,
            color: 'var(--pdt-ink)',
            outline: 'none',
          }}
        />
        {suffix && (
          <span style={{
            padding: '12px 14px', borderLeft: '1px solid var(--pdt-line-soft)',
            fontFamily: 'var(--pdt-mono)', fontSize: 13,
            color: 'var(--pdt-mute)', background: 'var(--pdt-paper-deep)',
            display: 'flex', alignItems: 'center',
          }}>
            {suffix}
          </span>
        )}
      </div>
    </label>
  );
}

// --- MoneyField ---
// Like NumberField but formats the displayed value with comma separators.
// Uses a text input internally; strips non-digit characters on change.
function MoneyField({ label, hint, value, onChange, min, max, step = 1, suffix, prefix }) {
  const allowDecimal = step < 1;
  const formatVal = (v) => {
    if (v === '' || v == null) return '';
    if (allowDecimal && typeof v === 'string') {
      const m = v.match(/^(-?\d*)(\.\d*)?$/);
      if (m) {
        const intPart = m[1] || '';
        const decPart = m[2] || '';
        const intFmt = intPart === '' || intPart === '-'
          ? intPart
          : Number(intPart).toLocaleString();
        return intFmt + decPart;
      }
    }
    if (typeof v === 'string') v = Number(v.replace(/,/g, ''));
    if (!isFinite(v)) return '';
    if (allowDecimal) {
      return v.toLocaleString(undefined, { maximumFractionDigits: 2 });
    }
    return Math.round(v).toLocaleString();
  };
  const handle = (e) => {
    const raw = e.target.value.replace(/,/g, '');
    if (raw === '') { onChange(''); return; }
    if (allowDecimal && /^\d*\.?\d*$/.test(raw)) {
      onChange(raw === '.' ? '' : raw);
    } else if (!allowDecimal && /^\d+$/.test(raw)) {
      onChange(Number(raw));
    } else if (allowDecimal && /^\d+(\.\d+)?$/.test(raw)) {
      onChange(Number(raw));
    }
  };
  return (
    <label style={{ display: 'block' }}>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        marginBottom: 8, gap: 12,
      }}>
        <span style={{
          fontFamily: 'var(--pdt-mono)', fontSize: 11,
          letterSpacing: '0.08em', textTransform: 'uppercase',
          color: 'var(--pdt-ink)',
        }}>
          {label}
        </span>
        {hint && (
          <span style={{
            fontFamily: 'var(--pdt-mono)', fontSize: 10,
            color: 'var(--pdt-mute)', textAlign: 'right',
          }}>
            {hint}
          </span>
        )}
      </div>
      <div style={{
        display: 'flex', alignItems: 'stretch',
        border: '1px solid var(--pdt-line)',
        background: '#fff',
      }}>
        {prefix && (
          <span style={{
            padding: '12px 14px', borderRight: '1px solid var(--pdt-line-soft)',
            fontFamily: 'var(--pdt-mono)', fontSize: 13,
            color: 'var(--pdt-mute)', background: 'var(--pdt-paper-deep)',
            display: 'flex', alignItems: 'center',
          }}>
            {prefix}
          </span>
        )}
        <input
          type="text"
          inputMode="decimal"
          value={formatVal(value)}
          onChange={handle}
          style={{
            flex: 1, minWidth: 0,
            padding: '12px 14px',
            border: 'none', background: 'transparent',
            fontFamily: 'var(--pdt-sans)', fontSize: 18,
            fontWeight: 500,
            color: 'var(--pdt-ink)',
            outline: 'none',
          }}
        />
        {suffix && (
          <span style={{
            padding: '12px 14px', borderLeft: '1px solid var(--pdt-line-soft)',
            fontFamily: 'var(--pdt-mono)', fontSize: 13,
            color: 'var(--pdt-mute)', background: 'var(--pdt-paper-deep)',
            display: 'flex', alignItems: 'center',
          }}>
            {suffix}
          </span>
        )}
      </div>
    </label>
  );
}

// --- SplitField ---
// Slider that splits 100% between two named sides (e.g. Doctor / Hygiene).
// `value` is the left-side percentage; right side is derived as 100 - value.
function SplitField({ label, hint, leftLabel, rightLabel, value, onChange }) {
  return (
    <div>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        marginBottom: 8, gap: 12,
      }}>
        <span style={{
          fontFamily: 'var(--pdt-mono)', fontSize: 11,
          letterSpacing: '0.08em', textTransform: 'uppercase',
          color: 'var(--pdt-ink)',
        }}>
          {label}
        </span>
        {hint && (
          <span style={{
            fontFamily: 'var(--pdt-mono)', fontSize: 10,
            color: 'var(--pdt-mute)', textAlign: 'right',
          }}>
            {hint}
          </span>
        )}
      </div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 14,
        background: '#fff', border: '1px solid var(--pdt-line)',
        padding: '10px 14px',
      }}>
        <input
          type="range"
          min={0} max={100} step={5}
          value={value}
          onChange={(e) => onChange(Number(e.target.value))}
          style={{ flex: 1, accentColor: 'var(--pdt-forest)' }}
        />
        <div style={{
          fontFamily: 'var(--pdt-mono)', fontSize: 13,
          color: 'var(--pdt-ink)', whiteSpace: 'nowrap',
          minWidth: 110, textAlign: 'right',
        }}>
          <span style={{ color: 'var(--pdt-forest)', fontWeight: 500 }}>{value}%</span>
          <span style={{ color: 'var(--pdt-mute)' }}> {leftLabel}</span>
        </div>
      </div>
      <div style={{
        marginTop: 6, fontFamily: 'var(--pdt-mono)', fontSize: 11,
        color: 'var(--pdt-mute)', display: 'flex', justifyContent: 'space-between',
      }}>
        <span>{leftLabel}: {value}%</span>
        <span>{rightLabel}: {100 - value}%</span>
      </div>
    </div>
  );
}

// --- ResultPanel ---
// Right-hand result card. Headline number in forest green, breakdown rows below,
// optional italic footnote at the bottom.
function ResultPanel({ headlineLabel, headlineValue, headlineSub, breakdown, footnote }) {
  return (
    <div style={{
      background: 'var(--pdt-mint)',
      border: '1px solid var(--pdt-sage)',
      padding: 'clamp(28px, 4vw, 48px)',
      position: 'relative',
    }}>
      <div className="t-eyebrow" style={{
        color: 'var(--pdt-forest-deep)',
        marginBottom: 18,
      }}>
        {headlineLabel}
      </div>
      <div style={{
        fontFamily: 'var(--pdt-sans)',
        fontSize: 'clamp(48px, 8vw, 88px)',
        fontWeight: 500,
        letterSpacing: '-0.025em',
        lineHeight: 1,
        color: 'var(--pdt-forest-deep)',
        marginBottom: 8,
      }}>
        {headlineValue}
      </div>
      {headlineSub && (
        <div style={{
          fontFamily: 'var(--pdt-serif)', fontStyle: 'italic',
          fontSize: 'clamp(15px, 1.6vw, 17px)',
          color: 'var(--pdt-forest-deep)', opacity: 0.8,
          marginBottom: 32,
        }}>
          {headlineSub}
        </div>
      )}
      {breakdown && breakdown.length > 0 && (
        <div style={{
          marginTop: 24, paddingTop: 24,
          borderTop: '1px solid var(--pdt-sage)',
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))',
          gap: 24,
        }}>
          {breakdown.map((row, i) => (
            <div key={i}>
              <div className="t-eyebrow" style={{
                color: 'var(--pdt-forest-deep)', opacity: 0.7,
                marginBottom: 8, fontSize: 10,
              }}>
                {row.label}
              </div>
              <div style={{
                fontSize: 22, fontWeight: 500,
                color: 'var(--pdt-forest-deep)',
                letterSpacing: '-0.01em',
              }}>
                {row.value}
              </div>
              {row.sub && (
                <div style={{
                  fontSize: 12, color: 'var(--pdt-forest-deep)', opacity: 0.7,
                  marginTop: 4, fontFamily: 'var(--pdt-mono)',
                }}>
                  {row.sub}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
      {footnote && (
        <div style={{
          marginTop: 28, paddingTop: 20,
          borderTop: '1px solid var(--pdt-sage)',
          fontFamily: 'var(--pdt-serif)', fontStyle: 'italic',
          fontSize: 14, lineHeight: 1.55,
          color: 'var(--pdt-forest-deep)', opacity: 0.85,
        }}>
          {footnote}
        </div>
      )}
    </div>
  );
}

// --- ToolFooter ---
// Bottom section: what this tool deliberately doesn't measure (left) +
// soft CTA + optional related insight link (right card).
function ToolFooter({ doesntMeasure, ctaText, ctaHref, relatedInsight }) {
  return (
    <section style={{
      padding: 'clamp(40px, 6vw, 80px) clamp(16px, 4vw, 32px) clamp(48px, 8vw, 96px)',
      maxWidth: 1280, margin: '0 auto',
      borderTop: '1px solid var(--pdt-line)',
    }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
        gap: 'clamp(28px, 4vw, 56px)',
      }}>
        <div>
          <div className="t-eyebrow" style={{ marginBottom: 16, color: 'var(--pdt-mute)' }}>
            What this tool doesn't measure
          </div>
          <p style={{
            fontFamily: 'var(--pdt-serif)',
            fontSize: 17, lineHeight: 1.6,
            color: 'var(--pdt-ink-soft)', margin: 0,
          }}>
            {doesntMeasure}
          </p>
        </div>

        {(ctaText || relatedInsight) && (
          <div style={{
            background: 'var(--pdt-paper-deep)',
            border: '1px solid var(--pdt-line)',
            padding: 'clamp(24px, 3vw, 32px)',
          }}>
            {ctaText && (
              <>
                <div className="t-eyebrow" style={{ marginBottom: 12, color: 'var(--pdt-mute)' }}>
                  Want the real number?
                </div>
                <p style={{
                  fontSize: 17, lineHeight: 1.55, margin: '0 0 18px',
                  color: 'var(--pdt-ink)',
                }}>
                  {ctaText}
                </p>
                <a href={ctaHref} style={{
                  display: 'inline-block',
                  fontFamily: 'var(--pdt-mono)', fontSize: 12,
                  letterSpacing: '0.08em', textTransform: 'uppercase',
                  color: 'var(--pdt-forest)',
                  textDecoration: 'none',
                  borderBottom: '1px solid var(--pdt-forest)',
                  paddingBottom: 2,
                }}>
                  Get in touch →
                </a>
              </>
            )}
            {relatedInsight && (
              <div style={{
                marginTop: ctaText ? 28 : 0,
                paddingTop: ctaText ? 24 : 0,
                borderTop: ctaText ? '1px solid var(--pdt-line-soft)' : 'none',
              }}>
                <div className="t-eyebrow" style={{ marginBottom: 10, color: 'var(--pdt-mute)' }}>
                  Related reading
                </div>
                <a href={relatedInsight.href} style={{
                  display: 'block',
                  fontSize: 16, lineHeight: 1.4,
                  color: 'var(--pdt-ink)',
                  textDecoration: 'none',
                  borderBottom: '1px solid var(--pdt-line)',
                  paddingBottom: 8,
                }}>
                  <span style={{ borderBottom: '1px solid var(--pdt-forest)' }}>
                    {relatedInsight.title}
                  </span>
                </a>
              </div>
            )}
          </div>
        )}
      </div>
    </section>
  );
}

// --- ToolReference ---
// "The terms, briefly" + "Why you should care" — optional, place above ToolFooter.
function ToolReference({ glossary, whyCare }) {
  return (
    <section style={{
      padding: 'clamp(40px, 6vw, 72px) clamp(16px, 4vw, 32px)',
      maxWidth: 1280, margin: '0 auto',
    }}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))',
        gap: 'clamp(28px, 4vw, 56px)',
      }}>
        {glossary && glossary.length > 0 && (
          <div>
            <div className="t-eyebrow" style={{ marginBottom: 20, color: 'var(--pdt-mute)' }}>
              The terms, briefly
            </div>
            <dl style={{ margin: 0 }}>
              {glossary.map((item, i) => (
                <div key={i} style={{
                  paddingBottom: 18, marginBottom: 18,
                  borderBottom: i === glossary.length - 1
                    ? 'none'
                    : '1px solid var(--pdt-line-soft)',
                }}>
                  <dt style={{
                    fontFamily: 'var(--pdt-sans)',
                    fontSize: 16, fontWeight: 600,
                    letterSpacing: '-0.01em',
                    color: 'var(--pdt-ink)',
                    marginBottom: 6,
                  }}>
                    {item.term}
                  </dt>
                  <dd style={{
                    margin: 0,
                    fontFamily: 'var(--pdt-serif)',
                    fontSize: 16, lineHeight: 1.55,
                    color: 'var(--pdt-ink-soft)',
                  }}>
                    {item.definition}
                  </dd>
                </div>
              ))}
            </dl>
          </div>
        )}
        {whyCare && (
          <div>
            <div className="t-eyebrow" style={{ marginBottom: 20, color: 'var(--pdt-mute)' }}>
              Why you should care
            </div>
            <div style={{
              fontFamily: 'var(--pdt-serif)',
              fontSize: 18, lineHeight: 1.65,
              color: 'var(--pdt-ink)',
            }}>
              {whyCare}
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

// Export all components to window so downstream tool scripts can reference them
// without a module bundler (Babel standalone transpiles JSX but doesn't bundle imports).
window.ToolPageHeader  = ToolPageHeader;
window.ToolFrame       = ToolFrame;
window.InputCard       = InputCard;
window.NumberField     = NumberField;
window.MoneyField      = MoneyField;
window.SplitField      = SplitField;
window.ResultPanel     = ResultPanel;
window.ToolFooter      = ToolFooter;
window.ToolReference   = ToolReference;
window.fmtMoney        = fmtMoney;
window.fmtMoneyFull    = fmtMoneyFull;
window.fmtPct          = fmtPct;
