// Shared small bits — TrustStat, HowItWorksStepper, ProblemCard, Rule,
// SectionLabel — usable from either variation. All take a `palette` prop so
// each variation can tint them.

// Responsive helper: returns true when the viewport is at or below `bp` px.
// Uses matchMedia + change events; SSR-safe-ish (defaults to false on server).
function useIsMobile(bp) {
  const breakpoint = bp || 768;
  const query = `(max-width: ${breakpoint - 1}px)`;
  const [isMobile, setIsMobile] = React.useState(() => {
    if (typeof window === 'undefined' || !window.matchMedia) return false;
    return window.matchMedia(query).matches;
  });
  React.useEffect(() => {
    if (typeof window === 'undefined' || !window.matchMedia) return;
    const mq = window.matchMedia(query);
    const onChange = (e) => setIsMobile(e.matches);
    if (mq.addEventListener) mq.addEventListener('change', onChange);
    else mq.addListener(onChange);
    setIsMobile(mq.matches);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener('change', onChange);
      else mq.removeListener(onChange);
    };
  }, [query]);
  return isMobile;
}
window.useIsMobile = useIsMobile;

function Rule({ palette, style }) {
  return <div style={{ height: 1, background: palette.rule, ...style }} />;
}

function SectionLabel({ palette, num, children, style }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14,
      fontFamily: '"Inter", ui-sans-serif, system-ui, sans-serif',
      fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase',
      color: palette.mute, fontWeight: 600, ...style,
    }}>
      {num && <span style={{color: palette.accent, fontVariantNumeric:'tabular-nums'}}>{num}</span>}
      <span>{children}</span>
      <span style={{flex:1, height:1, background: palette.rule, marginLeft:4}}/>
    </div>
  );
}

// Big percentage card — echoes the pitch deck page 2
function TrustStat({ palette, value, caption, source }) {
  return (
    <div style={{
      borderTop: `1px solid ${palette.rule}`,
      paddingTop: 28,
      display: 'flex', flexDirection: 'column', gap: 18,
      fontFamily: '"Inter", ui-sans-serif, system-ui, sans-serif',
    }}>
      <div style={{
        fontFamily: '"Source Serif Pro", "Source Serif 4", Georgia, serif',
        fontSize: 120, lineHeight: 0.95, letterSpacing: '-0.04em',
        color: palette.ink, fontWeight: 400,
      }}>{value}</div>
      <div style={{ fontSize: 16, lineHeight: 1.45, color: palette.ink, maxWidth: 360, fontWeight: 400 }}>
        {caption}
      </div>
      <div style={{ fontSize: 10.5, letterSpacing: '0.16em', color: palette.mute, textTransform: 'uppercase', fontWeight: 600 }}>
        {source}
      </div>
    </div>
  );
}

function ProblemCard({ palette, num, title, points }) {
  return (
    <div style={{
      padding: '28px 28px 32px',
      background: palette.cardBg,
      border: `1px solid ${palette.rule}`,
      fontFamily: '"Inter", ui-sans-serif, system-ui, sans-serif',
      display: 'flex', flexDirection: 'column', gap: 18,
      minHeight: 320,
    }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
        <span style={{ fontSize: 10.5, letterSpacing: '0.2em', color: palette.mute, fontWeight: 600, textTransform:'uppercase' }}>
          {num}
        </span>
        <span style={{ fontSize: 10.5, letterSpacing: '0.2em', color: palette.accent, fontWeight: 600, textTransform:'uppercase' }}>
          Blocker
        </span>
      </div>
      <h3 style={{
        fontFamily: '"Source Serif Pro", "Source Serif 4", Georgia, serif',
        fontSize: 26, lineHeight: 1.12, letterSpacing: '-0.015em',
        color: palette.ink, fontWeight: 400, margin: 0,
      }}>{title}</h3>
      <ul style={{ listStyle:'none', padding: 0, margin: 0, display:'flex', flexDirection:'column', gap: 10 }}>
        {points.map((p,i)=>(
          <li key={i} style={{ display:'flex', gap: 12, fontSize: 13.5, lineHeight: 1.5, color: palette.body }}>
            <span style={{color: palette.accent, marginTop: 2, flex:'0 0 auto'}}>—</span>
            <span>{p}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

// Clickable 6-step "How it works" — step-through with full ARIA tab semantics
function HowItWorksStepper({ palette, accentStrong = false }) {
  const isMobile = useIsMobile();
  const [active, setActive] = React.useState(0);
  const tabRefs = React.useRef([]);
  const steps = [
    { n:'01', k:'Discover',  h:'The right creators, identified.',
      wall: null,
      d:'We map patient and HCP creators against your brand, indication, and audience goals. Every candidate is scored on fit, reach quality, and prior tone.' },
    { n:'02', k:'Vet',       h:'Deep background, before contracts.',
      wall: 'Addresses Wall 02 · Reputational risk, affiliations, prior content',
      d:'Credibility, affiliations, prior content, and reputational risk — reviewed by humans and AI before your brand or legal team ever sees a name.' },
    { n:'03', k:'Onboard',   h:'Briefed on compliance, not just brand.',
      wall: 'Addresses Wall 01 · Compliance upstream of creative',
      d:'Creators are trained on your indications, guardrails, and tone before they begin drafting. Fewer revision cycles later.' },
    { n:'04', k:'Create',    h:'MLR-ready review, built in.',
      wall: 'Addresses Wall 01 · Compliance in the critical path',
      d:'Every asset runs through an Eddy pre-review before it reaches your MLR team. Inline comments, versioning, direct handoff to your system of record.' },
    { n:'05', k:'Monitor',   h:'Adverse events, always watched.',
      wall: 'Addresses Wall 03 · Operational complexity, absorbed',
      d:'Ongoing monitoring and a rapid-response playbook for every post. Surfaced in your dashboard the moment a flag hits.' },
    { n:'06', k:'Optimize',  h:'Next campaign starts smarter.',
      wall: null,
      d:'Performance by creator, asset, and indication feeds the next brief — benchmarked against the wider Eddy network.' },
  ];

  const focusTab = (i) => {
    const el = tabRefs.current[i];
    if (el && typeof el.focus === 'function') el.focus();
  };

  const onKeyDown = (e) => {
    let next = null;
    if (e.key === 'ArrowRight') next = (active + 1) % steps.length;
    else if (e.key === 'ArrowLeft') next = (active - 1 + steps.length) % steps.length;
    else if (e.key === 'Home') next = 0;
    else if (e.key === 'End') next = steps.length - 1;
    if (next !== null) {
      e.preventDefault();
      setActive(next);
      // focus the newly-active tab on next paint
      setTimeout(() => focusTab(next), 0);
    }
  };

  return (
    <div style={{ fontFamily: '"Inter", ui-sans-serif, system-ui, sans-serif' }}>
      {/* step rail */}
      <div
        role="tablist"
        aria-label="How Eddy works — six stages"
        onKeyDown={onKeyDown}
        className={isMobile ? 'dash-scroll' : ''}
        style={{
          display: isMobile ? 'flex' : 'grid',
          gridTemplateColumns: isMobile ? undefined : 'repeat(6, 1fr)',
          overflowX: isMobile ? 'auto' : 'visible',
          scrollSnapType: isMobile ? 'x mandatory' : undefined,
          borderTop: `1px solid ${palette.rule}`, borderBottom: `1px solid ${palette.rule}`,
        }}
      >
        {steps.map((s, i) => {
          const isActive = i === active;
          return (
            <button
              key={s.n}
              ref={(el) => { tabRefs.current[i] = el; }}
              role="tab"
              id={`how-tab-${i}`}
              aria-selected={isActive}
              aria-controls={`how-panel-${i}`}
              tabIndex={isActive ? 0 : -1}
              onClick={() => setActive(i)}
              onMouseEnter={isMobile ? undefined : () => setActive(i)}
              style={{
                all: 'unset', cursor: 'pointer',
                padding: isMobile ? '16px 18px' : '20px 18px',
                flex: isMobile ? '0 0 auto' : undefined,
                minWidth: isMobile ? 130 : undefined,
                scrollSnapAlign: isMobile ? 'start' : undefined,
                borderRight: i < 5 ? `1px solid ${palette.rule}` : 'none',
                background: isActive ? palette.stepActive : 'transparent',
                color: isActive ? palette.ink : palette.body,
                display: 'flex', flexDirection: 'column', gap: 8,
                position: 'relative', transition: 'background .15s',
              }}
            >
              <div style={{
                fontSize: 10.5, letterSpacing: '0.2em', textTransform: 'uppercase',
                color: isActive ? palette.accent : palette.mute, fontWeight: 600,
              }}>{s.n}</div>
              <div style={{
                fontFamily: '"Source Serif Pro", "Source Serif 4", Georgia, serif',
                fontSize: 20, letterSpacing: '-0.015em', lineHeight: 1.1, fontWeight: 400,
              }}>{s.k}</div>
              {isActive && accentStrong && (
                <div style={{
                  position:'absolute', left: 0, right: 0, bottom: -1, height: 2,
                  background: palette.accent,
                }}/>
              )}
            </button>
          );
        })}
      </div>

      {/* active detail (tabpanel) */}
      <div
        role="tabpanel"
        id={`how-panel-${active}`}
        aria-labelledby={`how-tab-${active}`}
        style={{
          padding: isMobile ? '32px 4px 8px' : '44px 24px 8px',
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : '1fr 2fr',
          gap: isMobile ? 28 : 60,
          minHeight: isMobile ? 0 : 220,
        }}
      >
        <div>
          <div style={{ fontSize: 10.5, letterSpacing: '0.2em', textTransform: 'uppercase', color: palette.mute, fontWeight: 600, marginBottom: 14 }}>
            Step {steps[active].n} of 06
          </div>
          <div style={{
            fontFamily: '"Source Serif Pro", "Source Serif 4", Georgia, serif',
            fontSize: 'clamp(32px, 6vw, 44px)', letterSpacing: '-0.02em', lineHeight: 1.0, color: palette.ink, fontWeight: 400,
          }}>
            {steps[active].k}
          </div>
          <div style={{ marginTop: 24, display: 'flex', gap: 6 }}>
            {steps.map((_, i) => (
              <button
                key={i}
                onClick={()=>setActive(i)}
                aria-label={`Go to step ${i+1}: ${steps[i].k}`}
                style={{
                  all:'unset', cursor:'pointer',
                  width: i===active ? 24 : 8, height: 8,
                  background: i===active ? palette.accent : palette.rule,
                  borderRadius: 99, transition: 'all .2s',
                }}
              />
            ))}
          </div>
        </div>
        <div style={{ maxWidth: 560 }}>
          <div style={{
            fontFamily: '"Source Serif Pro", "Source Serif 4", Georgia, serif',
            fontSize: 'clamp(22px, 3.5vw, 28px)', lineHeight: 1.2, letterSpacing: '-0.015em', color: palette.ink,
            fontWeight: 400, marginBottom: 18,
          }}>
            {steps[active].h}
          </div>
          <div style={{ fontSize: 15.5, lineHeight: 1.6, color: palette.body }}>
            {steps[active].d}
          </div>
          {steps[active].wall && (
            <div style={{
              marginTop: 22, paddingTop: 16,
              borderTop: `1px dashed ${palette.rule}`,
              display:'flex', alignItems:'center', gap: 10,
              fontFamily: '"Inter", sans-serif', fontSize: 10.5,
              letterSpacing: '0.2em', textTransform: 'uppercase',
              color: palette.accent, fontWeight: 600,
            }}>
              <span style={{
                width: 5, height: 5, background: palette.accent, borderRadius: 99, flex:'0 0 auto'
              }}/>
              <span>{steps[active].wall}</span>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.Rule = Rule;
window.SectionLabel = SectionLabel;
window.TrustStat = TrustStat;
window.ProblemCard = ProblemCard;
window.HowItWorksStepper = HowItWorksStepper;
