/* global React */
// Shared UI primitives — tokens, layout chrome, form controls.
const { useState, useRef, useEffect } = React;

// ─────────────────────────────────────────────────────────────
// Tokens
// ─────────────────────────────────────────────────────────────
function paosTokens(primary, surface) {
  const warm = surface === 'warm';
  return {
    primary,
    primarySoft: primary + '14',
    primaryMid: primary + '33',
    primaryDeep: '#1d3854',
    bg: warm ? '#F4EFE6' : '#F4F4F2',
    surface: '#FFFFFF',
    ink: '#0F1E2E',
    inkSoft: '#5B6B7D',
    inkFaint: '#A4ADB7',
    line: 'rgba(15,30,46,0.08)',
    lineStrong: 'rgba(15,30,46,0.14)',
    accent: '#C6A26A',
    danger: '#C44A3A',
  };
}

// ─────────────────────────────────────────────────────────────
// Header — back button + step label + 7-segment progress
// ─────────────────────────────────────────────────────────────
function StepProgress({ step, total, t }) {
  return (
    <div style={{ display: 'flex', gap: 5, padding: '0 24px', marginTop: 6 }}>
      {Array.from({ length: total }).map((_, i) => (
        <div key={i} style={{
          flex: 1, height: 6, borderRadius: 3,
          background: i <= step ? t.primary : 'rgba(15,30,46,0.14)',
          boxShadow: i <= step ? `0 1px 2px ${t.primary}40` : 'none',
          transition: 'background 360ms ease',
        }} />
      ))}
    </div>
  );
}

function Header({ step, total, onBack, t, canBack, stepName }) {
  return (
    <div style={{ paddingTop: 56, paddingBottom: 14, flexShrink: 0 }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '0 24px 10px',
      }}>
        <button
          onClick={onBack}
          disabled={!canBack}
          style={{
            width: 36, height: 36, borderRadius: 18, border: 'none',
            background: canBack ? t.primarySoft : 'transparent',
            color: canBack ? t.primary : t.inkFaint,
            cursor: canBack ? 'pointer' : 'default',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            transition: 'background 200ms',
          }}
        >
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M10 3L5 8L10 13" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <div style={{
          fontFamily: 'Geist Mono, monospace',
          fontSize: 11, fontWeight: 500, letterSpacing: '0.1em',
          color: t.inkSoft, textTransform: 'uppercase',
          textAlign: 'center', display: 'flex', flexDirection: 'column',
        }}>
          <span>Step {step + 1} of {total}</span>
          {stepName && <span style={{ color: t.primary, marginTop: 2, fontSize: 10 }}>· {stepName} ·</span>}
        </div>
        <div style={{ width: 36 }} />
      </div>
      <StepProgress step={step} total={total} t={t} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Sub-progress for voice steps (Question X of N)
// ─────────────────────────────────────────────────────────────
function SubProgress({ index, total, t }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <div style={{ display: 'flex', gap: 4, flex: 1 }}>
        {Array.from({ length: total }).map((_, i) => (
          <div key={i} style={{
            flex: 1, height: 4, borderRadius: 2,
            background: i <= index ? t.primary : t.line,
            transition: 'background 260ms',
          }} />
        ))}
      </div>
      <div style={{
        fontFamily: 'Geist Mono, monospace', fontSize: 11,
        color: t.inkSoft, letterSpacing: '0.05em', flexShrink: 0,
      }}>
        Q {index + 1} / {total}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Buttons
// ─────────────────────────────────────────────────────────────
function PrimaryButton({ children, onClick, disabled, t, variant = 'primary', size = 'lg' }) {
  const isPrimary = variant === 'primary';
  const h = size === 'sm' ? 44 : 56;
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      style={{
        width: '100%', height: h, borderRadius: h / 2,
        border: isPrimary ? 'none' : `1px solid ${t.lineStrong}`,
        background: disabled ? t.line : (isPrimary ? t.primary : 'transparent'),
        color: disabled ? t.inkFaint : (isPrimary ? '#fff' : t.primary),
        fontFamily: 'Geist, system-ui, sans-serif',
        fontSize: size === 'sm' ? 15 : 16, fontWeight: 600, letterSpacing: '-0.01em',
        cursor: disabled ? 'default' : 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        transition: 'transform 120ms ease, background 200ms',
      }}
      onMouseDown={(e) => !disabled && (e.currentTarget.style.transform = 'scale(0.98)')}
      onMouseUp={(e) => (e.currentTarget.style.transform = 'scale(1)')}
      onMouseLeave={(e) => (e.currentTarget.style.transform = 'scale(1)')}
    >
      {children}
    </button>
  );
}

function GhostLink({ children, onClick, t }) {
  return (
    <button
      onClick={onClick}
      style={{
        background: 'transparent', border: 'none', padding: 0,
        fontFamily: 'Geist, system-ui, sans-serif',
        fontSize: 14, fontWeight: 500, color: t.inkSoft,
        cursor: 'pointer', textDecoration: 'underline',
        textDecorationColor: t.line, textUnderlineOffset: 4,
      }}
    >
      {children}
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// Field label
// ─────────────────────────────────────────────────────────────
function FieldLabel({ index, label, hint, t, optional }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <div style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
        {index != null && (
          <span style={{
            fontFamily: 'Geist Mono, monospace', fontSize: 10,
            color: t.inkFaint, fontWeight: 500, paddingTop: 2,
            letterSpacing: '0.05em',
          }}>
            {String(index).padStart(2, '0')}
          </span>
        )}
        <label style={{
          fontFamily: 'Geist, system-ui, sans-serif', fontSize: 14,
          fontWeight: 500, color: t.ink, letterSpacing: '-0.005em',
          textWrap: 'pretty', flex: 1,
        }}>
          {label}
          {optional && (
            <span style={{ color: t.inkFaint, fontWeight: 400 }}> · optional</span>
          )}
        </label>
      </div>
      {hint && (
        <div style={{
          fontFamily: 'Geist, system-ui, sans-serif',
          fontSize: 12.5, color: t.inkSoft, marginTop: 4,
          paddingLeft: index != null ? 24 : 0, lineHeight: 1.45,
        }}>
          {hint}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// TextField (single-line)
// ─────────────────────────────────────────────────────────────
function TextField({ value, onChange, placeholder, t, type = 'text', icon }) {
  const [focused, setFocused] = useState(false);
  return (
    <div style={{ position: 'relative' }}>
      {icon && (
        <div style={{
          position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)',
          color: focused ? t.primary : t.inkFaint, transition: 'color 200ms',
          pointerEvents: 'none', display: 'flex',
        }}>{icon}</div>
      )}
      <input
        type={type}
        value={value || ''}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        style={{
          width: '100%', height: 50, borderRadius: 12,
          border: `1.5px solid ${focused ? t.primary : t.line}`,
          padding: icon ? '0 16px 0 42px' : '0 16px',
          fontFamily: 'Geist, system-ui, sans-serif', fontSize: 15,
          color: t.ink, background: t.surface, outline: 'none',
          transition: 'border-color 180ms', boxSizing: 'border-box',
        }}
      />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// TextArea (multi-line)
// ─────────────────────────────────────────────────────────────
function TextArea({ value, onChange, placeholder, t, rows = 3 }) {
  const [focused, setFocused] = useState(false);
  return (
    <textarea
      value={value || ''}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      onFocus={() => setFocused(true)}
      onBlur={() => setFocused(false)}
      rows={rows}
      style={{
        width: '100%', borderRadius: 14,
        border: `1.5px solid ${focused ? t.primary : t.line}`,
        padding: 14,
        fontFamily: 'Geist, system-ui, sans-serif', fontSize: 15,
        color: t.ink, background: t.surface, outline: 'none',
        transition: 'border-color 180ms', boxSizing: 'border-box',
        resize: 'none', lineHeight: 1.5,
      }}
    />
  );
}

// ─────────────────────────────────────────────────────────────
// Chips — multi or single select
// ─────────────────────────────────────────────────────────────
function Chips({ options, value, onChange, t, multi = true, max }) {
  const isOn = (o) => multi ? (value || []).includes(o) : value === o;
  const toggle = (o) => {
    if (!multi) { onChange(o); return; }
    const cur = value || [];
    if (cur.includes(o)) onChange(cur.filter(x => x !== o));
    else if (max == null || cur.length < max) onChange([...cur, o]);
  };
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
      {options.map(o => {
        const on = isOn(o);
        return (
          <button
            key={o}
            onClick={() => toggle(o)}
            style={{
              height: 34, padding: '0 12px', borderRadius: 17,
              border: `1.5px solid ${on ? t.primary : t.line}`,
              background: on ? t.primary : t.surface,
              color: on ? '#fff' : t.ink,
              fontFamily: 'Geist, system-ui, sans-serif',
              fontSize: 13, fontWeight: 500, cursor: 'pointer',
              transition: 'all 160ms ease',
              display: 'flex', alignItems: 'center', gap: 4,
            }}
          >
            {on && multi && (
              <svg width="11" height="11" viewBox="0 0 11 11"><path d="M1.5 5.5L4 8L9.5 2.5" stroke="#fff" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
            )}
            {o}
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Segmented control (single-select, vertical-friendly fallback)
// Compact horizontal scroll if too many options to fit
// ─────────────────────────────────────────────────────────────
function Segmented({ options, value, onChange, t, columns }) {
  // For 5+ options or long labels use a wrap-grid; for ≤4 use a row
  const useGrid = columns || options.length > 4;
  return (
    <div style={{
      display: useGrid ? 'grid' : 'flex',
      gridTemplateColumns: useGrid ? `repeat(${columns || Math.min(3, options.length)}, 1fr)` : undefined,
      gap: 6,
      padding: 4, borderRadius: 14, background: t.bg,
      border: `1px solid ${t.line}`,
    }}>
      {options.map(o => {
        const on = value === o;
        return (
          <button
            key={o}
            onClick={() => onChange(o)}
            style={{
              minHeight: 38, padding: '0 10px', borderRadius: 10, border: 'none',
              background: on ? t.surface : 'transparent',
              color: on ? t.primary : t.inkSoft,
              fontFamily: 'Geist, system-ui, sans-serif',
              fontSize: 13, fontWeight: on ? 600 : 500,
              cursor: 'pointer',
              boxShadow: on ? '0 1px 4px rgba(15,30,46,0.08)' : 'none',
              transition: 'all 180ms ease',
              whiteSpace: 'nowrap',
            }}
          >
            {o}
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Dropdown — bottom sheet style picker (mock)
// ─────────────────────────────────────────────────────────────
function Dropdown({ options, value, onChange, t, placeholder = 'Select…' }) {
  const [open, setOpen] = useState(false);
  return (
    <>
      <button
        onClick={() => setOpen(true)}
        style={{
          width: '100%', height: 50, borderRadius: 12,
          border: `1.5px solid ${value ? t.primary : t.line}`,
          padding: '0 16px', background: t.surface,
          fontFamily: 'Geist, system-ui, sans-serif', fontSize: 15,
          color: value ? t.ink : t.inkFaint,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          cursor: 'pointer', textAlign: 'left',
        }}
      >
        <span>{value || placeholder}</span>
        <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 5l4 4 4-4" stroke={t.inkSoft} strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </button>
      {open && (
        <div
          onClick={() => setOpen(false)}
          style={{
            position: 'absolute', inset: 0, zIndex: 100,
            background: 'rgba(15,30,46,0.4)',
            display: 'flex', alignItems: 'flex-end',
            animation: 'fadeIn 200ms ease both',
          }}
        >
          <div
            onClick={(e) => e.stopPropagation()}
            style={{
              width: '100%', background: t.surface,
              borderTopLeftRadius: 24, borderTopRightRadius: 24,
              padding: '18px 16px 28px',
              animation: 'slideUp 280ms cubic-bezier(.2,.9,.3,1) both',
              maxHeight: '70%', overflowY: 'auto',
            }}
          >
            <div style={{
              width: 44, height: 4, background: t.line, borderRadius: 2,
              margin: '0 auto 14px',
            }} />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {options.map(o => (
                <button
                  key={o}
                  onClick={() => { onChange(o); setOpen(false); }}
                  style={{
                    height: 50, borderRadius: 12, border: 'none',
                    background: value === o ? t.primarySoft : 'transparent',
                    color: value === o ? t.primary : t.ink,
                    fontFamily: 'Geist, system-ui, sans-serif', fontSize: 15,
                    fontWeight: value === o ? 600 : 500,
                    textAlign: 'left', padding: '0 14px', cursor: 'pointer',
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  }}
                >
                  <span>{o}</span>
                  {value === o && (
                    <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 7l3.5 3.5L12 4" stroke={t.primary} strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  )}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// YesNoToggle with optional follow-up
// ─────────────────────────────────────────────────────────────
function YesNoToggle({ value, onChange, t }) {
  return (
    <div style={{ display: 'flex', gap: 8 }}>
      {['Yes', 'No'].map(opt => {
        const on = value === opt.toLowerCase();
        return (
          <button
            key={opt}
            onClick={() => onChange(opt.toLowerCase())}
            style={{
              flex: 1, height: 44, borderRadius: 12,
              border: `1.5px solid ${on ? t.primary : t.line}`,
              background: on ? t.primary : t.surface,
              color: on ? '#fff' : t.ink,
              fontFamily: 'Geist, system-ui, sans-serif',
              fontSize: 14, fontWeight: 600, cursor: 'pointer',
              transition: 'all 160ms ease',
            }}
          >
            {opt}
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Section header inside a long form
// ─────────────────────────────────────────────────────────────
function SectionDivider({ label, t }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      paddingTop: 8, paddingBottom: 4,
    }}>
      <span style={{
        fontFamily: 'Geist Mono, monospace', fontSize: 10,
        color: t.inkFaint, fontWeight: 500, letterSpacing: '0.1em',
        textTransform: 'uppercase',
      }}>{label}</span>
      <div style={{ flex: 1, height: 1, background: t.line }} />
    </div>
  );
}

// Export to window so other JSX files can use them.
Object.assign(window, {
  paosTokens, Header, StepProgress, SubProgress,
  PrimaryButton, GhostLink, FieldLabel,
  TextField, TextArea, Chips, Segmented, Dropdown, YesNoToggle,
  SectionDivider,
});
