// TimeBackCalculator — ICP-page interactive moment.
// One slider: hours per week of admin you don't need to be doing.
// Outputs: hours / workdays / weeks reclaimed per year.
// Frames it as time back for clients, planning, and family — picks up
// the language from the TimeBack marquee and the banner CTA.

const { useState: useStateTBC, useEffect: useEffectTBC } = React;

// Defensive analytics helper. If lib/analytics.js isn't loaded (e.g. on a
// page that forgot to include it), window.bluemoso.analytics is undefined
// and `.track(...)` throws TypeError — without an error boundary that takes
// the whole component subtree down, which is what happened on ICP pages
// when the user touched the calculator's slider. This wrapper no-ops
// instead of throwing so the calculator can never break for that reason.
function tbcTrack(name, params) {
  try {
    if (window.bluemoso && window.bluemoso.analytics && typeof window.bluemoso.analytics.track === 'function') {
      window.bluemoso.analytics.track(name, params);
    }
  } catch (e) {
    /* swallow — analytics failure must never break the UI */
  }
}

const tbcStyles = {
  section: {
    padding: 'var(--section-y) 32px',
    background: '#fff',
    position: 'relative',
  },
  inner: {
    maxWidth: 1180,
    margin: '0 auto',
    display: 'grid',
    gridTemplateColumns: '1fr 1fr',
    gap: 64,
    alignItems: 'center',
  },
  copyCol: {
    display: 'flex', flexDirection: 'column', gap: 18,
    maxWidth: 520,
  },
  eyebrow: {
    fontFamily: "'Outfit', system-ui, sans-serif",
    fontSize: 12, color: 'var(--blue)',
    letterSpacing: '0.14em', textTransform: 'uppercase',
    fontWeight: 500,
    display: 'inline-flex', alignItems: 'center', gap: 10,
    whiteSpace: 'nowrap',
  },
  eyebrowDot: {
    width: 6, height: 6, borderRadius: 999,
    background: 'var(--blue)',
    boxShadow: '0 0 0 4px rgba(8,120,216,0.16)',
  },
  h2: {
    fontFamily: "'Outfit', system-ui, sans-serif",
    fontSize: 'clamp(34px, 4vw, 56px)',
    lineHeight: 1.04,
    letterSpacing: '-0.025em',
    color: 'var(--ink)',
    fontWeight: 600,
    margin: 0,
    textWrap: 'balance',
  },
  h2Accent: { color: 'var(--blue)', fontWeight: 600 },
  sub: {
    fontSize: 16, lineHeight: 1.6,
    color: 'var(--ink-muted)',
    margin: 0,
    maxWidth: 460,
  },
  bullets: {
    marginTop: 6,
    display: 'flex', flexDirection: 'column', gap: 10,
    listStyle: 'none', padding: 0,
  },
  bullet: {
    display: 'flex', alignItems: 'flex-start', gap: 10,
    fontSize: 14, color: 'var(--ink-soft)', lineHeight: 1.55,
  },
  bulletDot: {
    flex: 'none',
    width: 18, height: 18, borderRadius: 9,
    background: 'rgba(8,120,216,0.12)',
    color: 'var(--blue)',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    fontSize: 10, fontWeight: 700, lineHeight: 1,
    marginTop: 2,
  },

  // CARD
  card: {
    background: '#fff',
    border: '1px solid var(--line-soft)',
    borderRadius: 20,
    padding: 28,
    boxShadow: 'var(--shadow-lg)',
    position: 'relative',
  },
  cardTitle: {
    fontFamily: "'Outfit', system-ui, sans-serif",
    fontSize: 26, lineHeight: 1.1,
    letterSpacing: '-0.02em',
    color: 'var(--ink)',
    fontWeight: 600,
    marginBottom: 6,
  },
  cardTitleAccent: {
    color: 'var(--blue)', fontWeight: 600,
  },
  cardSub: {
    fontSize: 13, color: 'var(--ink-muted)',
    lineHeight: 1.5,
    marginBottom: 22,
  },

  group: { marginBottom: 16 },
  label: {
    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    fontSize: 12, color: 'var(--ink-muted)', marginBottom: 8,
    fontWeight: 500, letterSpacing: '0.02em', textTransform: 'uppercase',
    gap: 12,
  },
  labelVal: {
    fontFamily: "'Outfit', system-ui, sans-serif",
    fontVariantNumeric: 'tabular-nums',
    fontSize: 14, color: 'var(--ink)',
    fontWeight: 600, textTransform: 'none', letterSpacing: 0,
    whiteSpace: 'nowrap',
  },
  // Stepper — number input flanked by -/+ buttons
  stepper: {
    display: 'flex', alignItems: 'stretch',
    border: '1px solid var(--line)',
    borderRadius: 12,
    overflow: 'hidden',
    background: '#fff',
    width: '100%',
    transition: 'border-color .15s, box-shadow .15s',
  },
  stepperBtn: {
    flex: 'none',
    width: 44,
    background: 'var(--blue-soft)',
    color: 'var(--blue-deep)',
    border: 'none',
    fontSize: 20,
    fontWeight: 500,
    fontFamily: "'Outfit', system-ui, sans-serif",
    lineHeight: 1,
    cursor: 'pointer',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    transition: 'background .15s, color .15s',
    userSelect: 'none',
  },
  stepperInput: {
    flex: 1, minWidth: 0,
    border: 'none', outline: 'none',
    background: 'transparent',
    textAlign: 'center',
    fontFamily: "'Outfit', system-ui, sans-serif",
    fontVariantNumeric: 'tabular-nums',
    fontSize: 22,
    fontWeight: 600,
    letterSpacing: '-0.01em',
    color: 'var(--ink)',
    padding: '12px 8px',
    appearance: 'textfield',
    MozAppearance: 'textfield',
  },
  stepperSuffix: {
    display: 'inline-flex', alignItems: 'center',
    paddingRight: 14,
    fontSize: 13, color: 'var(--ink-muted)',
    fontFamily: "'Outfit', system-ui, sans-serif",
    fontWeight: 500,
    letterSpacing: 0,
    textTransform: 'none',
  },
  stepperHint: {
    marginTop: 8,
    fontSize: 11, color: 'var(--ink-muted)',
    fontFamily: "'Outfit', system-ui, sans-serif",
    letterSpacing: '0.02em',
  },

  // HERO RESULT — coral/cream block matching TimeBack section
  hero: {
    marginTop: 18,
    padding: '28px 24px 24px',
    background: 'linear-gradient(160deg, #161B3D 0%, #0A1028 100%)',
    color: '#fff',
    borderRadius: 14,
    position: 'relative',
    overflow: 'hidden',
    textAlign: 'center',
  },
  heroGlow: {
    position: 'absolute', bottom: -80, left: -40, width: 240, height: 240,
    borderRadius: '50%',
    background: 'radial-gradient(circle, rgba(85,166,229,0.28) 0%, transparent 70%)',
    pointerEvents: 'none',
  },
  heroLabel: {
    fontSize: 10.5, color: 'rgba(255,255,255,0.8)',
    letterSpacing: '0.14em', textTransform: 'uppercase',
    fontWeight: 500,
    marginBottom: 8, position: 'relative',
  },
  heroNum: {
    fontFamily: "'Outfit', system-ui, sans-serif",
    fontSize: 'clamp(56px, 7vw, 84px)',
    lineHeight: 0.95,
    letterSpacing: '-0.035em',
    fontVariantNumeric: 'tabular-nums',
    color: '#fff',
    position: 'relative',
    whiteSpace: 'nowrap',
    fontWeight: 600,
  },
  heroUnit: {
    fontSize: 22, color: 'rgba(255,255,255,0.88)',
    fontFamily: "'Outfit', system-ui, sans-serif",
    marginLeft: 6,
    fontWeight: 500,
  },
  heroSub: {
    fontSize: 13, color: 'rgba(255,255,255,0.88)',
    lineHeight: 1.55,
    marginTop: 10,
    position: 'relative',
    maxWidth: 360,
    marginLeft: 'auto', marginRight: 'auto',
  },

  // Secondary chips (workdays / weeks equivalent)
  chips: {
    marginTop: 14,
    display: 'grid',
    gridTemplateColumns: '1fr 1fr',
    gap: 10,
  },
  chip: {
    padding: '12px 14px',
    background: 'var(--blue-soft)',
    border: '1px solid rgba(8,120,216,0.16)',
    borderRadius: 12,
    display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
    gap: 10,
  },
  chipLabel: {
    fontSize: 12, color: 'var(--blue-deep)',
    fontWeight: 500,
    textTransform: 'none', letterSpacing: 0,
  },
  chipVal: {
    fontFamily: "'Outfit', system-ui, sans-serif",
    fontVariantNumeric: 'tabular-nums',
    fontSize: 20, color: 'var(--blue-deep)',
    letterSpacing: '-0.01em',
    fontWeight: 600,
    whiteSpace: 'nowrap',
  },
  chipUnit: {
    fontSize: 12, color: 'var(--blue-deep)',
    opacity: 0.7,
    fontFamily: "'Outfit', system-ui, sans-serif",
    marginLeft: 2,
    fontWeight: 500,
  },

  footer: { marginTop: 16 },
  cta: {
    width: '100%', background: 'var(--blue)', color: '#fff',
    padding: '16px 20px', borderRadius: 12,
    fontSize: 15, fontWeight: 500,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    transition: 'background .2s, transform .12s, box-shadow .2s',
    boxShadow: '0 8px 20px -8px rgba(8,120,216,0.45)',
    letterSpacing: '-0.005em',
  },
  fine: {
    fontSize: 11, color: 'var(--ink-muted)', textAlign: 'center', marginTop: 10,
    fontFamily: "'Outfit', system-ui, sans-serif",
    fontVariantNumeric: 'tabular-nums',
    letterSpacing: '0.02em',
  },
};

function TimeBackCalculatorCard(props) {
  const copy = props.copy || {};
  const cardTitleLead = copy.cardTitleLead || 'How much time are you spending on work you could';
  const cardTitleAccent = copy.cardTitleAccent || 'hand off?';
  const cardSub = copy.cardSub || "Work someone else could easily do. We'll add it up across the year.";
  const heroLabel = copy.heroLabel || 'Time back per year';
  const heroSub = copy.heroSub || 'Hours back for clients, planning, family, and the work that actually matters.';
  const ctaLabel = copy.ctaLabel || 'Take back your time now';
  const ctaHref = copy.ctaHref || '#cta';
  const initialHours = typeof props.initialHours === 'number' ? props.initialHours : 10;

  const HOURS_MIN = 0;
  const HOURS_MAX = 80;
  const clampHours = (n) => {
    if (!Number.isFinite(n)) return HOURS_MIN;
    return Math.max(HOURS_MIN, Math.min(HOURS_MAX, Math.round(n)));
  };

  const [hoursPerWeek, setHoursPerWeek] = useStateTBC(clampHours(initialHours));
  // Mirror string so users can type freely (incl. transient empty / partial values)
  const [hoursInput, setHoursInput] = useStateTBC(String(clampHours(initialHours)));
  const WEEKS = 50;
  const hoursPerYear = hoursPerWeek * WEEKS;
  const workdays = hoursPerYear / 8;
  const workweeks = hoursPerYear / 40;

  const commitHours = (n) => {
    const v = clampHours(n);
    setHoursPerWeek(v);
    setHoursInput(String(v));
  };
  const step = (delta) => commitHours(hoursPerWeek + delta);

  // -- Analytics: track viewport entry + first interaction ------------------
  const cardRef = React.useRef(null);
  const viewedFiredRef = React.useRef(false);
  const interactedFiredRef = React.useRef(false);
  const initialHoursRef = React.useRef(initialHours);

  // Fire timeback_viewed once when card scrolls into view (50% visible).
  React.useEffect(() => {
    if (!cardRef.current || viewedFiredRef.current) return;
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting && !viewedFiredRef.current) {
          viewedFiredRef.current = true;
          tbcTrack('timeback_viewed', {
            page: window.location.pathname,
            initial_hours: initialHoursRef.current,
          });
          observer.disconnect();
        }
      });
    }, { threshold: 0.5 });
    observer.observe(cardRef.current);
    return () => observer.disconnect();
  }, []);

  // Fire timeback_interacted on first slider change from initial value.
  React.useEffect(() => {
    if (interactedFiredRef.current) return;
    if (hoursPerWeek === initialHoursRef.current) return;
    interactedFiredRef.current = true;
    tbcTrack('timeback_interacted', {
      page: window.location.pathname,
      hours_per_week: hoursPerWeek,
      direction: hoursPerWeek > initialHoursRef.current ? 'up' : 'down',
    });
  }, [hoursPerWeek]);

  return (
    <div style={tbcStyles.card} className="bm-tbc-card" ref={cardRef}>
      <style>{`
        input.bm-tbc-num::-webkit-outer-spin-button,
        input.bm-tbc-num::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
        .bm-tbc-stepper:focus-within { border-color: var(--blue) !important; box-shadow: 0 0 0 3px rgba(8,120,216,0.16); }
        .bm-tbc-stepper-btn:hover { background: var(--blue) !important; color: #fff !important; }
        .bm-tbc-stepper-btn:active { transform: translateY(1px); }
        .bm-tbc-stepper-btn:disabled { opacity: 0.4; cursor: not-allowed; }
        .bm-tbc-stepper-btn:disabled:hover { background: var(--blue-soft) !important; color: var(--blue-deep) !important; }
        @keyframes bmTbcPop { 0% { opacity: 0.45; transform: translateY(2px); } 60% { opacity: 1; transform: translateY(-1px); } 100% { opacity: 1; transform: translateY(0); } }
        .bm-tbc-pop { display: inline-block; animation: bmTbcPop .35s cubic-bezier(.2,.8,.2,1); }
        /* Mobile: shrink padding + title so the card fits narrow viewports
           (was overflowing past the right edge on phones). */
        @media (max-width: 640px) {
          .bm-tbc-card { padding: 18px !important; box-sizing: border-box !important; max-width: 100% !important; }
          .bm-tbc-card .bm-tbc-cardtitle { font-size: 22px !important; line-height: 1.15 !important; }
        }
      `}</style>

      <div style={tbcStyles.cardTitle} className="bm-tbc-cardtitle">
        {cardTitleLead}{' '}
        <span style={tbcStyles.cardTitleAccent}>{cardTitleAccent}</span>
      </div>
      <div style={tbcStyles.cardSub}>{cardSub}</div>

      <div style={tbcStyles.group}>
        <div style={tbcStyles.label}>
          <span>Admin hours per week</span>
          <span style={tbcStyles.labelVal}>{hoursPerWeek} hrs/wk</span>
        </div>
        <div style={tbcStyles.stepper} className="bm-tbc-stepper">
          <button
            type="button"
            className="bm-tbc-stepper-btn"
            style={tbcStyles.stepperBtn}
            onClick={() => step(-1)}
            disabled={hoursPerWeek <= HOURS_MIN}
            aria-label="Decrease admin hours per week"
          >−</button>
          <input
            type="number"
            inputMode="numeric"
            className="bm-tbc-num"
            min={HOURS_MIN}
            max={HOURS_MAX}
            step={1}
            value={hoursInput}
            onChange={(e) => {
              const raw = e.target.value;
              // Allow empty / partial input while typing; only commit a numeric value.
              if (raw === '') { setHoursInput(''); return; }
              if (!/^\d{1,3}$/.test(raw)) return;
              setHoursInput(raw);
              const n = Number(raw);
              if (Number.isFinite(n)) setHoursPerWeek(clampHours(n));
            }}
            onBlur={() => commitHours(Number(hoursInput))}
            onKeyDown={(e) => {
              if (e.key === 'Enter') { e.currentTarget.blur(); }
              if (e.key === 'ArrowUp') { e.preventDefault(); step(1); }
              if (e.key === 'ArrowDown') { e.preventDefault(); step(-1); }
            }}
            style={tbcStyles.stepperInput}
            aria-label="Admin hours per week you don't need to be doing"
          />
          <span style={tbcStyles.stepperSuffix}>hrs / wk</span>
          <button
            type="button"
            className="bm-tbc-stepper-btn"
            style={tbcStyles.stepperBtn}
            onClick={() => step(1)}
            disabled={hoursPerWeek >= HOURS_MAX}
            aria-label="Increase admin hours per week"
          >+</button>
        </div>
        <div style={tbcStyles.stepperHint}>Type a number, or use −/+.</div>
      </div>

      {/* HERO RESULT */}
      <div style={tbcStyles.hero}>
        <div style={tbcStyles.heroGlow} aria-hidden="true"></div>
        <div style={tbcStyles.heroLabel}>{heroLabel}</div>
        <div>
          <span key={`hpy-${hoursPerYear}`} style={tbcStyles.heroNum} className="bm-tbc-pop">
            {hoursPerYear.toLocaleString()}
          </span>
          <span style={tbcStyles.heroUnit}>hrs</span>
        </div>
        <div style={tbcStyles.heroSub}>{heroSub}</div>
      </div>

      {/* SECONDARY CHIPS */}
      <div style={tbcStyles.chips}>
        <div style={tbcStyles.chip}>
          <span style={tbcStyles.chipLabel}>That's</span>
          <span>
            <span key={`d-${Math.round(workdays)}`} style={tbcStyles.chipVal} className="bm-tbc-pop">
              {Math.round(workdays).toLocaleString()}
            </span>
            <span style={tbcStyles.chipUnit}>&nbsp;workdays</span>
          </span>
        </div>
        <div style={tbcStyles.chip}>
          <span style={tbcStyles.chipLabel}>Or</span>
          <span>
            <span key={`w-${workweeks.toFixed(1)}`} style={tbcStyles.chipVal} className="bm-tbc-pop">
              {workweeks % 1 === 0 ? workweeks.toFixed(0) : workweeks.toFixed(1)}
            </span>
            <span style={tbcStyles.chipUnit}>&nbsp;full work-weeks</span>
          </span>
        </div>
      </div>

      <div style={tbcStyles.footer}>
        <a
          href={ctaHref}
          data-booking-modal-trigger
          data-booking-source="icp_hero_calculator_cta"
          style={tbcStyles.cta}
          onClick={() => {
            tbcTrack('timeback_cta_clicked', {
              page: window.location.pathname,
              hours_per_week: hoursPerWeek,
              hours_per_year: hoursPerYear,
              workdays: Math.round(workdays),
              workweeks: Math.round(workweeks * 10) / 10,
              interacted: interactedFiredRef.current,
              cta_href: ctaHref,
            });
          }}
          onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--blue-deep)'; e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = '0 14px 28px -10px rgba(8,120,216,0.55)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.background = 'var(--blue)'; e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 8px 20px -8px rgba(8,120,216,0.45)'; }}
        >
          {ctaLabel}
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M3 8h10m0 0l-4-4m4 4l-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </a>
        <div style={tbcStyles.fine}>Based on a 50-week year</div>
      </div>
    </div>
  );
}

function TimeBackCalculator(props) {
  const copy = props.copy || {};
  const eyebrow = copy.eyebrow || 'Calculator';
  const h2Lead = copy.h2Lead || 'How much time could you';
  const h2Accent = copy.h2Accent || 'get back?';
  const sub = copy.sub || "Pick the hours per week you're spending on work you don't need to be doing. We'll add it up across the year.";
  const bullets = copy.bullets || [
    'Review-meeting prep and CRM hygiene',
    'Scheduling, follow-ups, paperwork chases',
    'Newsletter, social, back-office admin',
  ];
  const cardTitle = copy.cardTitle || "Hours per week you don't need to be doing.";
  const cardSub = copy.cardSub || 'The admin work around your practice. Type in your hours.';
  const heroLabel = copy.heroLabel || 'Time back per year';
  const heroSub = copy.heroSub || 'Hours back for clients, planning, family, and the work that actually matters.';
  const ctaLabel = copy.ctaLabel || 'Take back your time now';
  const ctaHref = copy.ctaHref || '#cta';

  const initialHours = typeof props.initialHours === 'number' ? props.initialHours : 10;

  return (
    <section style={tbcStyles.section} className="reveal bm-section" id="time-calculator">
      <style>{`
        @media (max-width: 880px) {
          #time-calculator .bm-tbc-inner { grid-template-columns: 1fr !important; gap: 40px !important; }
        }
      `}</style>

      <div style={tbcStyles.inner} className="bm-tbc-inner">
        {/* COPY COLUMN */}
        <div style={tbcStyles.copyCol}>
          <span style={tbcStyles.eyebrow}>
            <span style={tbcStyles.eyebrowDot}></span>
            {eyebrow}
          </span>
          <h2 style={tbcStyles.h2}>
            {h2Lead} <span style={tbcStyles.h2Accent}>{h2Accent}</span>
          </h2>
          <p style={tbcStyles.sub}>{sub}</p>
          <ul style={tbcStyles.bullets}>
            {bullets.map((b, i) => (
              <li key={i} style={tbcStyles.bullet}>
                <span style={tbcStyles.bulletDot}>✓</span>
                <span>{b}</span>
              </li>
            ))}
          </ul>
        </div>

        {/* CALCULATOR CARD */}
        <TimeBackCalculatorCard copy={copy} initialHours={initialHours} />
      </div>
    </section>
  );
}

Object.assign(window, { TimeBackCalculator, TimeBackCalculatorCard });
