/* ============================================================
   THREDLY — Auth shell & shared form pieces
   AuShell renders the split card (dark brand scene left, form
   right). Plus the wordmark, password helpers, and the 2FA code
   input. Pinned to window so each page app can use them.
   ============================================================ */
const { useState: useAu, useRef: useAuRef, useEffect: useAuEffect } = React;

/* canonical Thredly wordmark — lowercase Geist word logo (T01) */
function AuWordmark({ height = 26, tone = 'dark' }) {
  const color = tone === 'light' ? '#fff' : 'var(--ink)';
  return (
    <span aria-label="Thredly" role="img" style={{
      fontFamily: "'Playfair Display', Georgia, serif", fontWeight: 700,
      fontSize: Math.round(height * 1.3), lineHeight: 1, letterSpacing: '-0.01em',
      color, display: 'inline-block', whiteSpace: 'nowrap'
    }}>thredly</span>);

}

/* the dark left scene — either floating product cards, or a
   numbered "what happens next" preview when `steps` is given */
function AuScene({ eyebrow, title, sub, steps }) {
  if (steps && steps.length) {
    return (
      <aside className="au-side">
        <div className="au-brand"><AuWordmark height={24} tone="light" /></div>
        <div className="au-side-copy" style={{ marginTop: '34px' }}>
          {eyebrow && <div className="au-eyebrow">{eyebrow}</div>}
          <h2 className="au-side-title">{title}</h2>
          {sub && <p className="au-side-sub">{sub}</p>}
        </div>
        <ol className="au-steps">
          {steps.map((s, i) =>
          <li key={i} className="au-step">
              <span className="au-step-num">{i + 1}</span>
              <span className="au-step-text">
                <span className="au-step-lbl">{s.label}</span>
                <span className="au-step-sub">{s.sub}</span>
              </span>
            </li>
          )}
        </ol>
        <div className="au-side-foot">Takes about 5 minutes. You can change anything later.</div>
      </aside>);

  }
  return (
    <aside className="au-side">
      <div className="au-brand"><AuWordmark height={24} tone="light" /></div>

      <div className="au-scene" aria-hidden="true">
        <div className="au-fcard c1">
          <div className="au-fc-head">
            <div className="au-fc-code">COMP101</div>
            <div className="au-fc-title">Intro to Computing</div>
          </div>
          <div className="au-fc-body">
            <div className="au-fc-line"></div>
            <div className="au-fc-line s"></div>
            <div className="au-fc-week">● Week 6 · live</div>
          </div>
        </div>

        <div className="au-fcard c2">
          <div className="au-fc-row">
            <span className="au-fc-ico sage"><Icon.calendar size={17} /></span>
            <div>
              <div className="au-fc-lbl">Workshop</div>
              <div className="au-fc-meta">Thu · 2:00pm · Lab 3</div>
            </div>
          </div>
        </div>

        <div className="au-fcard c3">
          <div className="au-fc-avatars">
            <span></span><span></span><span></span><span></span>
          </div>
          <div className="au-fc-lbl" style={{ marginTop: '9px' }}>248 enrolled</div>
        </div>
      </div>

      <div className="au-side-copy" style={{ width: "364px", textAlign: "left", alignSelf: "center", margin: "50px 0px 0px" }}>
        {eyebrow && <div className="au-eyebrow">{eyebrow}</div>}
        <h2 className="au-side-title">{title}</h2>
        {sub && <p className="au-side-sub">{sub}</p>}
      </div>
      <div className="au-side-foot">Course landing pages that always know what week it is.</div>
    </aside>);

}

function AuShell({ scene, children, narrow }) {
  return (
    <React.Fragment>
      <AuStyles />
      <div className="au-shell">
        <div className={'au-card' + (narrow ? ' narrow' : '')}>
          <AuScene {...scene} />
          <div className="au-main"><div className="au-main-inner">{children}</div></div>
        </div>
      </div>
    </React.Fragment>);

}

/* top row inside the form column: mobile brand + optional back link */
function AuTop({ back }) {
  return (
    <div className="au-top">
      <div className="au-top-brand"><AuWordmark height={22} tone="dark" /></div>
      {back ?
      <a className="au-back" href={back.href}><Icon.chevRight size={16} style={{ transform: 'rotate(180deg)' }} /> {back.label}</a> :
      <span></span>}
    </div>);

}

/* password field with show/hide */
function AuPw({ id, value, onChange, placeholder, autoComplete, onEnter }) {
  const [show, setShow] = useAu(false);
  return (
    <div className="au-inwrap au-pw">
      <input id={id} className="au-input" type={show ? 'text' : 'password'} value={value}
      onChange={(e) => onChange(e.target.value)} placeholder={placeholder} autoComplete={autoComplete}
      onKeyDown={(e) => {if (e.key === 'Enter' && onEnter) onEnter();}} />
      <button type="button" className="au-eye" onClick={() => setShow((s) => !s)} aria-label={show ? 'Hide password' : 'Show password'}>
        <Icon.eye size={18} />
      </button>
    </div>);

}

function auPwStrength(pw) {
  let s = 0;
  if (pw.length >= 8) s++;
  if (/[A-Z]/.test(pw) && /[a-z]/.test(pw)) s++;
  if (/\d/.test(pw)) s++;
  if (/[^A-Za-z0-9]/.test(pw)) s++;
  if (pw.length >= 12) s = Math.max(s, 3);
  return Math.min(s, 4);
}
const AU_PW_LABELS = ['Too short', 'Weak', 'Fair', 'Good', 'Strong'];

function AuStrength({ pw }) {
  if (!pw) return null;
  const s = auPwStrength(pw);
  return (
    <div className="au-strength">
      <div className="au-strength-bars">
        {[0, 1, 2, 3].map((i) => <span key={i} className={'au-bar' + (i < s ? ' on s' + s : '')} />)}
      </div>
      <span className={'au-strength-lbl s' + s}>{AU_PW_LABELS[s]}</span>
    </div>);

}

/* check / agree control */
function AuCheck({ on, onToggle, children, block }) {
  return (
    <button type="button" className={'au-check' + (on ? ' on' : '') + (block ? ' block' : '')} onClick={onToggle}>
      <span className="au-check-box">{on && <Icon.check size={13} />}</span>
      <span>{children}</span>
    </button>);

}

/* 6-box code input for 2FA */
function AuCode({ length = 6, value, onChange, err, onComplete }) {
  const refs = useAuRef([]);
  const set = (i, v) => {
    v = v.replace(/\D/g, '');
    if (!v) {const arr = value.split('');arr[i] = '';onChange(arr.join('').padEnd(0));return;}
    const arr = value.padEnd(length, ' ').split('');
    // support paste of multiple digits
    const digits = v.split('');
    let idx = i;
    digits.forEach((d) => {if (idx < length) {arr[idx] = d;idx++;}});
    const next = arr.join('').replace(/ /g, '');
    onChange(next.slice(0, length));
    const focusAt = Math.min(idx, length - 1);
    if (refs.current[focusAt]) refs.current[focusAt].focus();
    if (next.replace(/\s/g, '').length >= length && onComplete) onComplete(next.slice(0, length));
  };
  const key = (i, e) => {
    if (e.key === 'Backspace' && !value[i] && i > 0) refs.current[i - 1] && refs.current[i - 1].focus();
    if (e.key === 'ArrowLeft' && i > 0) refs.current[i - 1].focus();
    if (e.key === 'ArrowRight' && i < length - 1) refs.current[i + 1].focus();
  };
  /* 3.3.8: pasting a full code must work — maxLength=1 truncates pasted text
     before onChange sees it, so distribute the digits ourselves */
  const paste = (i, e) => {
    const txt = ((e.clipboardData || window.clipboardData).getData('text') || '').replace(/\D/g, '');
    if (!txt) return;
    e.preventDefault();
    set(i, txt);
  };
  useAuEffect(() => {if (refs.current[0]) refs.current[0].focus();}, []);
  return (
    <div className={'au-code' + (err ? ' err' : '')}>
      {Array.from({ length }).map((_, i) =>
      <input key={i} ref={(el) => refs.current[i] = el} inputMode="numeric" maxLength={1}
      autoComplete={i === 0 ? 'one-time-code' : 'off'}
      className={value[i] ? 'filled' : ''} value={value[i] || ''}
      onChange={(e) => set(i, e.target.value)} onKeyDown={(e) => key(i, e)} onPaste={(e) => paste(i, e)}
      onFocus={(e) => e.target.select()} aria-label={'Digit ' + (i + 1)} />
      )}
    </div>);

}

Object.assign(window, {
  AuWordmark, AuScene, AuShell, AuTop, AuPw, AuStrength, AuCheck, AuCode,
  auPwStrength, AU_PW_LABELS
});