// Shared UI components for the Glenwood Hub

const { useState, useEffect, useRef, useMemo, useCallback } = React;

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    const handler = () => setWidth(window.innerWidth);
    window.addEventListener("resize", handler);
    return () => window.removeEventListener("resize", handler);
  }, []);
  return width;
}
const BP = { sm: 640, md: 900 };

// Eagle mascot — inline <img> from /assets/eagle.svg
function Eagle({ size = 120, style = {}, className = "" }) {
  return (
    <img
      src="assets/eagle.svg"
      alt="Glenwood Eagle mascot"
      width={size}
      style={{ display: "block", ...style }}
      className={className}
    />
  );
}

// Chunky label-and-number chip ("LESSON 4" etc)
function Chip({ children, tone = "green", style = {} }) {
  const tones = {
    green:   { bg: "var(--green-700)", fg: "var(--gold-300)" },
    gold:    { bg: "var(--gold-500)",  fg: "var(--green-800)" },
    coral:   { bg: "var(--accent-coral)", fg: "#fff" },
    sky:     { bg: "var(--accent-sky)", fg: "#0c2a19" },
    outline: { bg: "transparent", fg: "var(--green-800)", border: "2px solid var(--green-800)" },
  };
  const t = tones[tone] || tones.green;
  return (
    <span className="mono" style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "5px 10px", borderRadius: 999,
      background: t.bg, color: t.fg, border: t.border || "0",
      fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 600,
      ...style,
    }}>{children}</span>
  );
}

// Primary button with animated press
function Button({ children, variant = "primary", onClick, style = {}, disabled, icon }) {
  const variants = {
    primary: {
      bg: "var(--green-700)", fg: "var(--gold-300)",
      shadow: "0 4px 0 var(--green-900)",
      hoverShadow: "0 6px 0 var(--green-900)",
    },
    gold: {
      bg: "var(--gold-500)", fg: "var(--green-800)",
      shadow: "0 4px 0 #a39b7a",
      hoverShadow: "0 6px 0 #a39b7a",
    },
    coral: {
      bg: "var(--accent-coral)", fg: "#fff",
      shadow: "0 4px 0 #a5532e",
      hoverShadow: "0 6px 0 #a5532e",
    },
    ghost: {
      bg: "transparent", fg: "var(--green-800)",
      shadow: "inset 0 0 0 2px var(--green-800)",
      hoverShadow: "inset 0 0 0 2px var(--green-800), 0 4px 0 rgba(0,0,0,0.08)",
    },
  };
  const v = variants[variant] || variants.primary;
  const [hover, setHover] = useState(false);
  const [press, setPress] = useState(false);
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setPress(false); }}
      onMouseDown={() => setPress(true)}
      onMouseUp={() => setPress(false)}
      style={{
        display: "inline-flex", alignItems: "center", gap: 8,
        padding: "12px 20px",
        background: v.bg, color: v.fg,
        borderRadius: 12,
        fontFamily: "Geist",
        fontWeight: 600, fontSize: 15,
        boxShadow: disabled ? "none" : (press
          ? v.shadow.replace("4px", "1px").replace("6px", "1px")
          : (hover ? v.hoverShadow : v.shadow)),
        transform: press ? "translateY(3px)" : (hover ? "translateY(-2px)" : "translateY(0)"),
        transition: "transform 120ms ease, box-shadow 120ms ease",
        opacity: disabled ? 0.45 : 1,
        cursor: disabled ? "not-allowed" : "pointer",
        ...style,
      }}
    >
      {icon}
      {children}
    </button>
  );
}

// Card — paper-feel container with dotted border accent
function Card({ children, style = {}, onClick, accent = "gold", interactive = false }) {
  const [hover, setHover] = useState(false);
  return (
    <div
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        background: "var(--paper)",
        borderRadius: 18,
        border: "1.5px solid rgba(24,71,44,0.15)",
        boxShadow: interactive
          ? (hover
              ? "0 12px 24px -8px rgba(12,42,25,0.25), 0 2px 0 rgba(24,71,44,0.1)"
              : "0 4px 0 rgba(24,71,44,0.08)")
          : "0 2px 0 rgba(24,71,44,0.08)",
        transform: interactive && hover ? "translateY(-3px)" : "translateY(0)",
        transition: "transform 200ms ease, box-shadow 200ms ease",
        cursor: interactive ? "pointer" : "default",
        ...style,
      }}
    >
      {children}
    </div>
  );
}

function HubHeader({ route, setRoute, studentName, onSignOut }) {
  const w = useWindowWidth();
  const isMobile = w < BP.sm;
  const [menuOpen, setMenuOpen] = useState(false);

  const navItems = [
    { key: "home",    label: "Home" },
    { key: "chat",    label: "SOARBot 9000" },
    { key: "quizzes", label: "Question Sets" },
  ];

  function navigate(key) { setRoute(key); setMenuOpen(false); }

  return (
    <header style={{
      background: "var(--green-800)",
      color: "var(--gold-300)",
      borderBottom: "3px solid var(--gold-500)",
      position: "sticky", top: 0, zIndex: 10,
    }}>
      <div style={{
        maxWidth: 1240, margin: "0 auto",
        padding: isMobile ? "12px 16px" : "14px 28px",
        display: "flex", alignItems: "center", gap: isMobile ? 12 : 24,
      }}>
        {/* Logo */}
        <button onClick={() => navigate("home")}
          style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer" }}>
          <div style={{
            width: 40, height: 40,
            background: "var(--gold-500)", borderRadius: 10,
            display: "grid", placeItems: "center",
            boxShadow: "0 3px 0 var(--green-900)", overflow: "hidden", flexShrink: 0,
          }}>
            <img src="assets/eagle.svg" alt="" style={{ width: 52, marginTop: 4 }} />
          </div>
          {!isMobile && (
            <div style={{ textAlign: "left" }}>
              <div className="serif" style={{ fontSize: 22, fontWeight: 800, color: "var(--gold-300)", lineHeight: 1 }}>
                Glenwood Eagles
              </div>
              <div className="mono" style={{ fontSize: 10, letterSpacing: "0.14em", color: "var(--gold-500)", marginTop: 4 }}>
                STUDENT HUB · MRS. MULLER · GRADE 6
              </div>
            </div>
          )}
        </button>

        {/* Desktop nav */}
        {!isMobile && (
          <nav style={{ marginLeft: "auto", display: "flex", gap: 4 }}>
            {navItems.map((n) => (
              <button key={n.key} onClick={() => navigate(n.key)}
                style={{
                  padding: "10px 16px", borderRadius: 10,
                  background: route === n.key ? "var(--gold-500)" : "transparent",
                  color: route === n.key ? "var(--green-800)" : "var(--gold-300)",
                  fontWeight: 600, fontSize: 14, transition: "background 150ms",
                }}
              >{n.label}</button>
            ))}
          </nav>
        )}

        {/* Desktop student badge */}
        {!isMobile && studentName && (
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <div className="mono" style={{
              padding: "6px 10px", borderRadius: 8,
              background: "rgba(212,204,170,0.14)",
              color: "var(--gold-500)", fontSize: 11,
              display: "flex", alignItems: "center", gap: 8,
            }}>
              <span style={{ width: 8, height: 8, background: "#6bd07f", borderRadius: 999 }} />
              {studentName.toUpperCase()}
            </div>
            <button onClick={onSignOut} title="Switch student"
              style={{ padding: "6px 10px", borderRadius: 8, color: "var(--gold-500)", fontSize: 11, fontWeight: 600, opacity: 0.6 }}
              onMouseEnter={e => e.currentTarget.style.opacity = 1}
              onMouseLeave={e => e.currentTarget.style.opacity = 0.6}
            >Sign out</button>
          </div>
        )}

        {/* Mobile hamburger */}
        {isMobile && (
          <button onClick={() => setMenuOpen(!menuOpen)}
            style={{ marginLeft: "auto", color: "var(--gold-300)", fontSize: 22, padding: "4px 8px", lineHeight: 1 }}>
            {menuOpen ? "✕" : "☰"}
          </button>
        )}
      </div>

      {/* Mobile dropdown nav */}
      {isMobile && menuOpen && (
        <div style={{
          background: "var(--green-900)",
          borderTop: "1px solid rgba(212,204,170,0.15)",
          padding: "8px 16px 12px",
        }}>
          {navItems.map((n) => (
            <button key={n.key} onClick={() => navigate(n.key)}
              style={{
                display: "block", width: "100%", textAlign: "left",
                padding: "12px 10px", borderRadius: 10,
                background: route === n.key ? "var(--gold-500)" : "transparent",
                color: route === n.key ? "var(--green-800)" : "var(--gold-300)",
                fontWeight: 600, fontSize: 15, marginBottom: 2,
              }}
            >{n.label}</button>
          ))}
          {studentName && (
            <button onClick={() => { onSignOut(); setMenuOpen(false); }}
              style={{
                display: "block", width: "100%", textAlign: "left",
                padding: "12px 10px", borderRadius: 10,
                color: "var(--gold-500)", fontWeight: 600, fontSize: 14,
                borderTop: "1px solid rgba(212,204,170,0.15)", marginTop: 6,
              }}
            >Sign out ({studentName})</button>
          )}
        </div>
      )}
    </header>
  );
}

// "Soar" stamp decoration
function SoarStamp({ style = {} }) {
  return (
    <div style={{
      width: 110, height: 110, borderRadius: 999,
      border: "2px dashed var(--green-700)",
      display: "grid", placeItems: "center",
      transform: "rotate(-8deg)",
      color: "var(--green-700)",
      ...style,
    }}>
      <div style={{ textAlign: "center" }}>
        <div className="serif" style={{ fontSize: 28, fontWeight: 900, letterSpacing: "0.02em", lineHeight: 1 }}>
          SOAR
        </div>
        <div className="mono" style={{ fontSize: 8, letterSpacing: "0.15em", marginTop: 4 }}>
          GLENWOOD · EST · 1962
        </div>
      </div>
    </div>
  );
}

// Inline name + email entry used on the home hero when no student is identified.
// Auto-fills name from localStorage if the email is recognised (returning student).
function EmailEntryForm({ onSubmit }) {
  const [name, setName]   = useState("");
  const [email, setEmail] = useState("");
  const [errors, setErrors] = useState({});

  function handleEmailBlur() {
    const v = email.trim();
    if (!v.includes("@")) return;
    try {
      const stored = localStorage.getItem(`glenwood_hub_${v}`);
      if (stored) {
        const data = JSON.parse(stored);
        if (data.name && !name.trim()) setName(data.name);
      }
    } catch {}
  }

  function handleSubmit(e) {
    e?.preventDefault();
    const n = name.trim(), em = email.trim();
    const errs = {};
    if (!n) errs.name = true;
    if (!em || !em.includes("@")) errs.email = true;
    if (Object.keys(errs).length) { setErrors(errs); return; }
    setErrors({});
    onSubmit({ name: n, email: em });
  }

  const inputStyle = (hasError) => ({
    padding: "13px 16px", borderRadius: 12,
    background: "rgba(255,253,245,0.12)",
    border: `2px solid ${hasError ? "var(--accent-coral)" : "var(--gold-500)"}`,
    color: "var(--gold-100)", fontSize: 16, fontFamily: "Geist",
    width: "100%", outline: "none",
  });

  return (
    <form onSubmit={handleSubmit} style={{ marginTop: 28, maxWidth: 400 }}>
      <p style={{ fontSize: 16, color: "var(--gold-200)", marginBottom: 16, opacity: 0.9 }}>
        Enter your name and school email to get started.
      </p>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        <input
          type="text"
          value={name}
          autoFocus
          autoComplete="given-name"
          placeholder="Your first name"
          onChange={e => { setName(e.target.value); setErrors(v => ({ ...v, name: false })); }}
          style={inputStyle(errors.name)}
        />
        <input
          type="email"
          value={email}
          autoComplete="email"
          placeholder="student@school.edu"
          onChange={e => { setEmail(e.target.value); setErrors(v => ({ ...v, email: false })); }}
          onBlur={handleEmailBlur}
          style={inputStyle(errors.email)}
        />
        <Button variant="gold" onClick={handleSubmit} style={{ alignSelf: "flex-start", marginTop: 4 }}>
          Let's go →
        </Button>
      </div>
      {(errors.name || errors.email) && (
        <p style={{ color: "var(--accent-coral)", fontSize: 13, marginTop: 8 }}>
          {errors.name && !errors.email ? "Please enter your name." :
           errors.email && !errors.name ? "Please enter a valid school email." :
           "Please enter your name and a valid school email."}
        </p>
      )}
    </form>
  );
}

Object.assign(window, { Eagle, Chip, Button, Card, HubHeader, SoarStamp, EmailEntryForm, useWindowWidth, BP });
