// screen-signin.jsx
// Sign-in gate: collects student identity before the briefing.
// Stores roster + completion records in localStorage under 'syl_override_v1'.

const { useState: useStSi } = React;

const STORAGE_KEY = 'syl_override_v1';

function loadRoster() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return { records: [] };
    return JSON.parse(raw);
  } catch { return { records: [] }; }
}

function saveCompletion(rec) {
  const data = loadRoster();
  data.records.push(rec);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
  if (window.SylFormsSync && window.SylFormsSync.postCompletion) {
    window.SylFormsSync.postCompletion(rec);
  }
}

function clearRoster() {
  localStorage.removeItem(STORAGE_KEY);
}

function SignInScreen({ onSignIn, onInstructor }) {
  const [name, setName] = useStSi('');
  const [email, setEmail] = useStSi('');
  const [section, setSection] = useStSi('04');
  const [touched, setTouched] = useStSi(false);

  const valid = name.trim().length >= 2 && /\S+@\S+\.\S+/.test(email);

  function submit(e) {
    e.preventDefault();
    setTouched(true);
    if (!valid) return;
    onSignIn({
      name: name.trim(),
      email: email.trim().toLowerCase(),
      section,
      signedInAt: Date.now(),
    });
  }

  return (
    <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 48, position: 'relative' }}>
      <div className="scan-line" />

      <div style={{ width: '100%', maxWidth: 540 }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div className="chip" style={{ marginBottom: 16 }}>◆ ACADEMY MAINFRAME // AUTH REQUIRED</div>
          <h1 className="t-display glow-cyan" style={{ fontSize: 44, letterSpacing: '0.04em' }}>
            IDENTIFY OPERATIVE
          </h1>
          <div style={{ color: 'var(--ink-60)', fontSize: 12, marginTop: 8, letterSpacing: '0.04em' }}>
            ◇ Credentials log to the instructor's roster. Use your university email.
          </div>
        </div>

        <form onSubmit={submit} className="panel" style={{ padding: 32, display: 'flex', flexDirection: 'column', gap: 18 }}>
          <Field label="Operative Callsign" hint="Real name as enrolled" error={touched && name.trim().length < 2}>
            <input value={name} onChange={(e) => setName(e.target.value)}
              placeholder="e.g. Alex Rivera"
              className="cyber-input" autoFocus />
          </Field>

          <Field label="Uplink Address" hint="@iu.edu university email" error={touched && !/\S+@\S+\.\S+/.test(email)}>
            <input value={email} onChange={(e) => setEmail(e.target.value)}
              placeholder="arivera@iu.edu" type="email"
              className="cyber-input" />
          </Field>

          <Field label="Section">
            <div style={{ display: 'flex', gap: 8 }}>
              {['01', '02', '03', '04'].map((s) => (
                <button type="button" key={s}
                  onClick={() => setSection(s)}
                  style={{
                    flex: 1, padding: '12px 0', cursor: 'pointer',
                    fontFamily: 'Orbitron, monospace', fontWeight: 700, fontSize: 13, letterSpacing: '0.1em',
                    background: section === s ? 'rgba(0,234,255,.18)' : 'rgba(0,0,0,.3)',
                    border: `1px solid ${section === s ? 'var(--neon-cyan)' : 'rgba(0,234,255,.25)'}`,
                    color: section === s ? 'var(--neon-cyan)' : 'var(--ink-60)',
                    boxShadow: section === s ? '0 0 16px rgba(0,234,255,.3)' : 'none',
                    transition: 'all .15s',
                  }}
                >SEC-{s}</button>
              ))}
            </div>
          </Field>

          <div style={{ fontSize: 10, color: 'var(--ink-60)', lineHeight: 1.6, padding: '12px 14px', background: 'rgba(0,0,0,.3)', borderLeft: '2px solid var(--neon-cyan)' }}>
            ◇ Your run will be logged to the instructor dashboard with completion time, score, badge, and grade. Privacy notice: stored locally on this device for demo purposes.
          </div>

          <button type="submit" className="btn btn-primary" disabled={!valid && touched} style={{ alignSelf: 'flex-end' }}>
            ► AUTHENTICATE
          </button>
        </form>

        <div style={{ textAlign: 'center', marginTop: 24 }}>
          <button onClick={onInstructor}
            style={{
              background: 'transparent', border: 0, cursor: 'pointer',
              color: 'var(--neon-magenta)', fontFamily: 'Orbitron, monospace',
              fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase',
              textShadow: '0 0 8px rgba(255,45,149,.4)',
            }}
          >
            ◇ INSTRUCTOR DASHBOARD →
          </button>
        </div>
      </div>

      <style>{`
        .cyber-input {
          width: 100%; padding: 12px 14px;
          background: rgba(0,0,0,.4);
          border: 1px solid rgba(0,234,255,.25);
          color: var(--ink-100);
          font-family: 'JetBrains Mono', monospace; font-size: 14px;
          letterSpacing: 0.02em; outline: none;
          transition: all .15s;
        }
        .cyber-input:focus {
          border-color: var(--neon-cyan);
          box-shadow: 0 0 16px rgba(0,234,255,.25);
          background: rgba(0,234,255,.04);
        }
        .cyber-input::placeholder { color: var(--ink-40); }
      `}</style>
    </div>
  );
}

function Field({ label, hint, error, children }) {
  const fieldId = React.useId();
  const errId = `${fieldId}-err`;
  const hintId = `${fieldId}-hint`;
  const describedBy = [hint && hintId, error && errId].filter(Boolean).join(' ') || undefined;
  const child = React.Children.only(children);
  const enhanced = React.cloneElement(child, {
    id: fieldId,
    'aria-invalid': error ? 'true' : 'false',
    'aria-describedby': describedBy,
    'aria-required': 'true',
  });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <label htmlFor={fieldId} style={{ display: 'flex',
        justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span className="t-display" style={{ fontSize: 10,
          color: error ? 'var(--neon-red)' : 'var(--neon-cyan)',
          letterSpacing: '0.16em' }}>
          <span aria-hidden="true">◇ </span>{label}
        </span>
        {hint && <span id={hintId} style={{ fontSize: 9,
          color: 'var(--ink-80)', letterSpacing: '0.08em' }}>{hint}</span>}
      </label>
      {enhanced}
      {error && (
        <span id={errId} role="alert" style={{ fontSize: 10,
          color: 'var(--neon-red)', letterSpacing: '0.04em' }}>
          <span aria-hidden="true">◇ </span>Required field — please complete
        </span>
      )}
    </div>
  );
}

window.SignInScreen = SignInScreen;
window.SylRosterStorage = { loadRoster, saveCompletion, clearRoster, STORAGE_KEY };
