/* eslint-disable */
// Common.jsx — shared utilities for the clickable prototype.
// Provides: PrototypeContext, hash-based routing, controllable OTP field,
// floating "Prototype menu" button, countdown timer, validation helpers.

const PrototypeContext = React.createContext({});
const usePrototype = () => React.useContext(PrototypeContext);

// ---------- Hash-based router ----------
// URL hash format: #<flow>/<screen>
//   #menu (or empty) → launcher
//   #onboarding/signup, #onboarding/email-verify, …
//   #mint/initiate, #mint/2fa, …
//   #dashboard/home, #dashboard/transactions, …
const useHashRoute = () => {
  const parse = () => {
    const h = window.location.hash.replace(/^#/, '');
    const [flow, screen] = h.split('/');
    return { flow: flow || 'menu', screen: screen || null };
  };
  const [route, setRoute] = React.useState(parse);
  React.useEffect(() => {
    const onChange = () => setRoute(parse());
    window.addEventListener('hashchange', onChange);
    return () => window.removeEventListener('hashchange', onChange);
  }, []);
  return route;
};

const navigateTo = (flow, screen) => {
  window.location.hash = screen ? `${flow}/${screen}` : flow;
};

// ---------- Controllable OTP input ----------
// A single hidden input drives a row of N segmented cells. Click anywhere
// in the row to focus; typing fills cells left-to-right; backspace deletes.
const OTPField = ({ value = '', onChange, length = 6, autoFocus, onComplete }) => {
  const ref = React.useRef(null);
  const [focused, setFocused] = React.useState(false);
  React.useEffect(() => {
    if (autoFocus && ref.current) {
      // Defer so the screen transition finishes first
      const t = setTimeout(() => ref.current && ref.current.focus(), 80);
      return () => clearTimeout(t);
    }
  }, [autoFocus]);
  const handle = (e) => {
    const v = e.target.value.replace(/\D/g, '').slice(0, length);
    onChange(v);
    if (v.length === length && onComplete) onComplete(v);
  };
  return (
    <div
      style={{ display: 'flex', gap: 8, position: 'relative', cursor: 'text', width: 'fit-content' }}
      onClick={() => ref.current && ref.current.focus()}
    >
      <input
        ref={ref}
        type="text"
        inputMode="numeric"
        autoComplete="one-time-code"
        value={value}
        onChange={handle}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        style={{
          position: 'absolute', opacity: 0, top: 0, left: 0,
          width: '100%', height: '100%',
          border: 'none', outline: 'none', background: 'transparent',
          cursor: 'text',
        }}
      />
      {Array.from({ length }).map((_, i) => {
        const ch = value[i];
        const isCurrent = focused && value.length === i;
        return (
          <div key={i} style={{
            width: 46, height: 54, borderRadius: 8,
            background: 'var(--ink-2)',
            border: `1px solid ${isCurrent || ch ? 'var(--border-gold)' : 'var(--border-default)'}`,
            boxShadow: isCurrent ? '0 0 0 2px rgba(201,152,64,0.15)' : 'none',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--font-mono)', fontSize: 22, fontWeight: 600,
            color: ch ? 'var(--fg-primary)' : 'var(--fg-tertiary)',
            position: 'relative',
            transition: 'border-color 120ms ease, box-shadow 120ms ease',
            pointerEvents: 'none',
          }}>
            {ch || ''}
            {isCurrent && !ch ? (
              <span style={{
                position: 'absolute', width: 1.5, height: 24, background: 'var(--gold-300)',
                animation: 'kgstPulse 1.1s ease-in-out infinite',
              }} />
            ) : null}
          </div>
        );
      })}
    </div>
  );
};

// ---------- Controllable text input with focus-gold treatment ----------
// Like the existing <Input> but with placeholder, real focus state.
const TextField = ({ label, value, onChange, placeholder, mono, type = 'text', prefix, suffix, helper, error, autoFocus, onEnter }) => {
  const [focused, setFocused] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (autoFocus && ref.current) {
      const t = setTimeout(() => ref.current && ref.current.focus(), 60);
      return () => clearTimeout(t);
    }
  }, [autoFocus]);
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {label ? <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{label}</span> : null}
      <div style={{
        display: 'flex', alignItems: 'center', height: 40, borderRadius: 6, overflow: 'hidden',
        border: `1px solid ${error ? 'rgba(196,69,69,0.55)' : focused ? 'var(--border-gold)' : 'var(--border-default)'}`,
        boxShadow: focused ? '0 0 0 3px rgba(201,152,64,0.10)' : 'none',
        background: 'var(--ink-2)',
        transition: 'border-color 120ms ease, box-shadow 120ms ease',
      }}>
        {prefix ? (
          <div style={{
            padding: '0 12px', height: '100%',
            display: 'inline-flex', alignItems: 'center',
            color: 'var(--bone-3)', fontSize: 12, fontFamily: 'var(--font-mono)',
            borderRight: '1px solid var(--border-subtle)',
          }}>{prefix}</div>
        ) : null}
        <input
          ref={ref}
          type={type}
          value={value || ''}
          placeholder={placeholder}
          onChange={e => onChange && onChange(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          onKeyDown={e => { if (e.key === 'Enter' && onEnter) onEnter(); }}
          style={{
            flex: 1, padding: '0 12px', height: '100%',
            background: 'transparent', border: 'none', outline: 'none',
            color: 'var(--fg-primary)',
            fontFamily: mono ? 'var(--font-mono)' : 'var(--font-sans)',
            fontSize: mono ? 13 : 14,
          }}
        />
        {suffix ? (
          <div style={{
            padding: '0 14px', height: '100%',
            display: 'inline-flex', alignItems: 'center',
            color: 'var(--gold-300)', fontSize: 12, fontFamily: 'var(--font-mono)',
            borderLeft: '1px solid var(--border-subtle)',
            background: 'var(--ink-3)',
          }}>{suffix}</div>
        ) : null}
      </div>
      {error ? (
        <span style={{ fontSize: 11, color: 'var(--red-400)' }}>{error}</span>
      ) : helper ? (
        <span style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>{helper}</span>
      ) : null}
    </label>
  );
};

// ---------- Custom checkbox ----------
const Checkbox = ({ checked, onChange, children }) => (
  <label style={{
    display: 'flex', alignItems: 'flex-start', gap: 10,
    fontSize: 12.5, color: 'var(--fg-secondary)', cursor: 'pointer',
    lineHeight: 1.5,
  }}>
    <span
      onClick={(e) => { e.preventDefault(); onChange(!checked); }}
      style={{
        width: 16, height: 16, marginTop: 2, borderRadius: 4, flexShrink: 0,
        background: checked ? 'var(--gold-400)' : 'var(--ink-2)',
        border: `1px solid ${checked ? 'var(--gold-500)' : 'var(--border-default)'}`,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        color: 'var(--ink-1)',
        transition: 'background 120ms ease, border-color 120ms ease',
      }}
    >
      {checked ? <Icons.check size={11} /> : null}
    </span>
    <span>{children}</span>
  </label>
);

// ---------- Floating "Prototype menu" button ----------
const PrototypeMenuButton = () => (
  <button
    onClick={() => navigateTo('menu')}
    style={{
      position: 'fixed', left: 16, bottom: 16, zIndex: 200,
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '8px 14px 8px 12px', borderRadius: 999,
      background: 'rgba(20,18,16,0.85)',
      backdropFilter: 'blur(8px)',
      WebkitBackdropFilter: 'blur(8px)',
      border: '1px solid var(--border-default)',
      color: 'var(--bone-4)', fontSize: 11,
      cursor: 'pointer',
      fontFamily: 'inherit',
      letterSpacing: '0.06em', textTransform: 'uppercase',
      transition: 'border-color 120ms ease, color 120ms ease',
    }}
    onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--border-gold)'; e.currentTarget.style.color = 'var(--gold-300)'; }}
    onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border-default)'; e.currentTarget.style.color = 'var(--bone-4)'; }}
  >
    <Icons.chevronRight size={11} style={{ transform: 'rotate(180deg)' }} />
    <span>Prototype menu</span>
  </button>
);

// ---------- MM:SS countdown ----------
const useCountdown = (initialSec) => {
  const [s, setS] = React.useState(initialSec);
  React.useEffect(() => {
    if (s <= 0) return;
    const t = setTimeout(() => setS(x => x - 1), 1000);
    return () => clearTimeout(t);
  }, [s]);
  const mm = String(Math.floor(s / 60)).padStart(2, '0');
  const ss = String(s % 60).padStart(2, '0');
  return { sec: s, label: `${mm}:${ss}`, reset: () => setS(initialSec) };
};

// ---------- After N ms, advance ----------
const useDelayedAdvance = (ms, onDone) => {
  React.useEffect(() => {
    const t = setTimeout(onDone, ms);
    return () => clearTimeout(t);
  }, []);  // eslint-disable-line
};

// ---------- Format a number with thousands separators while typing ----------
const formatAmount = (raw) => {
  if (!raw) return '';
  const clean = raw.replace(/[^\d.]/g, '');
  const [intPart, decPart] = clean.split('.');
  const withCommas = (intPart || '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  if (decPart !== undefined) return withCommas + '.' + decPart.slice(0, 2);
  return withCommas;
};
const parseAmount = (formatted) => Number((formatted || '0').replace(/,/g, '')) || 0;

Object.assign(window, {
  PrototypeContext, usePrototype, useHashRoute, navigateTo,
  OTPField, TextField, Checkbox, PrototypeMenuButton,
  useCountdown, useDelayedAdvance, formatAmount, parseAmount,
});
