/* === EnrollModal ===
 * Modal enrollment flow. Black scrim, no blur. Sharp-edged inputs.
 * Submit pretends to send and shows a terminal "SCAN COMPLETE" success state.
 */

const EnrollModal = ({ open, onClose }) => {
  const [stage, setStage] = React.useState("form"); // form | success
  const [form, setForm] = React.useState({
    unit: "", email: "", course: "Gray Man — OSRM 101", ack: false,
  });

  React.useEffect(() => {
    if (open) { setStage("form"); }
  }, [open]);

  if (!open) return null;

  const submit = (e) => {
    e.preventDefault();
    if (!form.unit || !form.email || !form.ack) return;
    setStage("success");
  };

  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "rgba(0,0,0,0.8)",
      display: "flex", alignItems: "center", justifyContent: "center",
      padding: 24,
    }}>
      <div onClick={(e) => e.stopPropagation()} className="enroll-modal-box" style={{
        position: "relative",
        background: "var(--obsidian-deep)",
        border: "1px solid var(--neon-magenta)",
        boxShadow: "var(--glow-magenta)",
        width: "100%", maxWidth: 840,
        display: "grid", gridTemplateColumns: "248px 1fr",
        overflow: "hidden",
      }}>
        <CornerTicks corners="tl tr bl br" color="var(--neon-magenta)" size={20}/>

        {/* Poster panel — the pack wading the loch at dusk. Hidden on narrow. */}
        <aside className="enroll-modal-poster" style={{
          position: "relative",
          backgroundImage: "url('../../assets/wallpaper-pack.png')",
          backgroundSize: "cover",
          backgroundPosition: "center 18%",
          borderRight: "1px solid var(--obsidian-fog)",
          minHeight: 460,
        }}>
          <div style={{
            position: "absolute", inset: 0,
            background: "linear-gradient(115deg, rgba(7,4,14,0) 45%, rgba(26,14,46,0.55) 100%)",
          }}/>
          <div style={{
            position: "absolute", left: 18, bottom: 18, right: 18,
            fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.24em",
            textTransform: "uppercase", color: "var(--fg-1)", textShadow: "0 1px 10px #000",
          }}>// The pack runs at dusk //</div>
        </aside>

        {/* Content column */}
        <div className="enroll-modal-content" style={{ position: "relative", padding: 36 }}>
        <button onClick={onClose} style={{
          position: "absolute", top: 18, right: 18,
          background: "transparent", border: "1px solid var(--obsidian-fog)",
          color: "var(--fg-2)", cursor: "pointer",
          width: 32, height: 32, padding: 0,
          fontFamily: "var(--font-mono)", fontSize: 14,
        }}>×</button>

        {stage === "form" ? (
          <>
            <Eyebrow>// Enrollment · OL-7 //</Eyebrow>
            <h3 style={{
              fontFamily: "var(--font-display)", fontSize: 36, lineHeight: 0.95,
              textTransform: "uppercase", color: "var(--fg-1)",
              margin: "10px 0 6px",
            }}>Reserve your seat</h3>
            <p style={{
              fontFamily: "var(--font-body)", fontSize: 13, lineHeight: 1.55,
              color: "var(--fg-3)", margin: "0 0 24px",
            }}>
              You'll receive a WARNO 7 days before the cohort begins. No marketing email; ever.
            </p>

            <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 18 }}>
              <Field label="// Unit //">
                <Input value={form.unit} onChange={(v) => setForm({ ...form, unit: v })} placeholder="e.g. 321st STS"/>
              </Field>
              <Field label="// Secure Email //">
                <Input type="email" value={form.email} onChange={(v) => setForm({ ...form, email: v })} placeholder="ops@example.org"/>
              </Field>
              <Field label="// Course //">
                <select
                  value={form.course}
                  onChange={(e) => setForm({ ...form, course: e.target.value })}
                  style={inputStyles()}>
                  <option>Gray Man — OSRM 101</option>
                  <option>Gray Ghost — OSRM Advanced</option>
                  <option>Sovereign Citizen</option>
                  <option>Down Range (Waitlist)</option>
                  <option>Technical Travel</option>
                  <option>Glass Eye — TPSC</option>
                </select>
              </Field>

              <label style={{
                display: "flex", gap: 10, alignItems: "center", cursor: "pointer",
                fontFamily: "var(--font-body)", fontSize: 13, color: "var(--fg-2)",
                userSelect: "none",
              }}>
                <span
                  onClick={() => setForm({ ...form, ack: !form.ack })}
                  style={{
                    width: 18, height: 18, position: "relative",
                    border: `1px solid ${form.ack ? "var(--neon-magenta)" : "var(--obsidian-fog)"}`,
                    background: form.ack ? "var(--neon-magenta)" : "#000",
                    boxShadow: form.ack ? "var(--glow-magenta-sm)" : "none",
                  }}>
                  {form.ack && (
                    <span style={{
                      position: "absolute", inset: 3, background: "#07040E",
                      clipPath: "polygon(15% 50%, 0 65%, 40% 100%, 100% 25%, 85% 10%, 40% 70%)",
                    }}></span>
                  )}
                </span>
                I have read the <a href="#" style={{ color: "var(--neon-cyan)" }}>OPSEC briefing</a>.
              </label>

              <div style={{ display: "flex", gap: 12, marginTop: 8 }}>
                <Button variant="primary" type="submit" icon="→">Submit</Button>
                <Button variant="ghost" onClick={onClose}>Cancel</Button>
              </div>
            </form>
          </>
        ) : (
          <SuccessTerminal unit={form.unit} course={form.course} onClose={onClose}/>
        )}
        </div>
      </div>

      <style>{`
        @media (max-width: 640px) {
          .enroll-modal-box { grid-template-columns: 1fr !important; }
          .enroll-modal-poster { display: none !important; }
        }
      `}</style>
    </div>
  );
};

const inputStyles = () => ({
  background: "#000",
  color: "var(--fg-1)",
  border: "1px solid var(--obsidian-fog)",
  padding: "10px 12px",
  fontFamily: "var(--font-mono)",
  fontSize: 13,
  width: "100%",
  borderRadius: 0,
  outline: "none",
});

const Input = ({ value, onChange, type = "text", placeholder }) => {
  const [focus, setFocus] = React.useState(false);
  return (
    <input
      type={type}
      value={value}
      placeholder={placeholder}
      onChange={(e) => onChange(e.target.value)}
      onFocus={() => setFocus(true)}
      onBlur={() => setFocus(false)}
      style={{
        ...inputStyles(),
        borderColor: focus ? "var(--neon-cyan)" : "var(--obsidian-fog)",
        boxShadow: focus ? "var(--glow-cyan)" : "none",
        color: focus ? "var(--neon-cyan)" : "var(--fg-1)",
      }}
    />
  );
};

const Field = ({ label, children }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
    <span style={{
      fontFamily: "var(--font-mono)", fontSize: 10,
      letterSpacing: "0.22em", textTransform: "uppercase",
      color: "var(--neon-magenta)",
    }}>{label}</span>
    {children}
  </div>
);

const SuccessTerminal = ({ unit, course, onClose }) => {
  const lines = [
    `> UNIT: ${unit.toUpperCase() || "OPERATOR"}`,
    `> COURSE: ${course.toUpperCase()}`,
    `> SCAN COMPLETE. RECORD WRITTEN.`,
    `> BRIEFING DISPATCHED. CHECK SECURE EMAIL.`,
    `> END.`,
  ];
  const [shown, setShown] = React.useState(0);
  React.useEffect(() => {
    if (shown < lines.length) {
      const t = setTimeout(() => setShown(shown + 1), 320);
      return () => clearTimeout(t);
    }
  }, [shown]);
  return (
    <div>
      <Eyebrow color="var(--signal-ok)">// Enrollment Confirmed //</Eyebrow>
      <h3 style={{
        fontFamily: "var(--font-display)", fontSize: 36, lineHeight: 0.95,
        textTransform: "uppercase", color: "var(--fg-1)",
        margin: "10px 0 16px",
      }}>You're in.</h3>
      <div style={{
        background: "#000", border: "1px solid var(--signal-ok)", padding: 18,
        boxShadow: "var(--glow-ok)",
      }}>
        {lines.slice(0, shown).map((l, i) => (
          <div key={i} style={{
            fontFamily: "var(--font-terminal), 'VT323', monospace", fontSize: 20,
            color: "var(--signal-ok)", textShadow: "0 0 8px currentColor",
            letterSpacing: "0.08em", lineHeight: 1.4,
          }}>{l}</div>
        ))}
        {shown < lines.length && (
          <span style={{
            display: "inline-block", width: 10, height: 18, background: "var(--signal-ok)",
            verticalAlign: "middle", animation: "ol-blink 800ms steps(2) infinite",
          }}></span>
        )}
      </div>
      <div style={{ marginTop: 24 }}>
        <Button variant="secondary" onClick={onClose}>Close</Button>
      </div>
      <style>{`@keyframes ol-blink { 0%, 50% { opacity: 1 } 50.01%, 100% { opacity: 0 } }`}</style>
    </div>
  );
};

Object.assign(window, { EnrollModal });
