const { useState, useEffect } = React;

const CONFIG = window.PROTO_CONFIG || {};
const BRAND = CONFIG.brand || "Konstruera";
const TAGLINE = CONFIG.tagline || "Beräkningsverktyg för konstruktörer";

const MENU_ITEMS = [
  { id: "takstol", label: "Takstolsdimensionering", hint: "EN 1995 · trätakstolar", href: "/verktyg/takstol/" },
  { id: "balk", label: "Balkdimensionering", hint: "Trä, stål och limträ", href: "/verktyg/balk/" },
  { id: "balk-klimat", label: "Balk – klimatdata", hint: "Boverkets klimatdatabas", href: "/verktyg/balk-klimat/" },
  { id: "bjalklag-klimat", label: "Bjälklag – klimatdata", hint: "Klimatpåverkan bjälklag", href: "/verktyg/bjalklag-klimat/" },
  { id: "betesplanering", label: "Betesplanering", hint: "Rotation, djur och journal", href: "/verktyg/betesplanering/" },
  { id: "grund", label: "Grundberäkning", hint: "Plintar, plattor, murar" },
  { id: "virke", label: "Virkesåtgång", hint: "Mängdning och inköpslista" },
  { id: "projekt", label: "Projekt", hint: "Mina ritningar och arkiv" },
];

function Logo({ size = 24 }) {
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round">
      <path d="M3 20 L12 4 L21 20 Z" />
      <path d="M7 20 L12 11 L17 20" />
    </svg>
  );
}

const URL_PARAMS = new URLSearchParams(window.location.search);
const INITIAL_VIEW = URL_PARAMS.get("view") === "home" || URL_PARAMS.get("menu") ? "home" : "login";
const INITIAL_MENU = URL_PARAMS.get("menu") === "1";

function App() {
  const [view, setView] = useState(INITIAL_VIEW);
  const [menuOpen, setMenuOpen] = useState(INITIAL_MENU);
  const [active, setActive] = useState(null);
  const [username, setUsername] = useState("");
  const [pw, setPw] = useState("");
  const [remember, setRemember] = useState(true);
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  // apps: null = unknown (preview/demo); ["*"] = super-user, sees all;
  // ["takstol", "balk-klimat"] etc. = explicit allowlist.
  const [apps, setApps] = useState(null);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") { setMenuOpen(false); setActive(null); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  // On load, ask the server if we're already logged in. If the endpoint doesn't
  // exist (offline preview), silently stay in demo mode.
  useEffect(() => {
    fetch("/api/me", { credentials: "same-origin" })
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (data && data.user) {
          setView("home");
          setApps(Array.isArray(data.apps) ? data.apps : ["*"]);
        }
      })
      .catch(() => {});
  }, []);

  const handleLogin = async () => {
    setError("");
    setBusy(true);
    try {
      const r = await fetch("/api/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "same-origin",
        body: JSON.stringify({ username, password: pw, remember }),
      });
      if (r.ok) {
        const data = await r.json().catch(() => ({}));
        setApps(Array.isArray(data.apps) ? data.apps : ["*"]);
        setView("home");
        return;
      }
      if (r.status === 401) { setError("Fel användarnamn eller lösenord."); return; }
      // Endpoint missing (offline preview) — fall through to demo behaviour.
      setView("home");
    } catch (e) {
      // Network error / no backend — demo mode
      setView("home");
    } finally {
      setBusy(false);
    }
  };

  const handleLogout = async () => {
    try { await fetch("/api/logout", { method: "POST", credentials: "same-origin" }); } catch (e) {}
    setView("login"); setMenuOpen(false); setActive(null);
  };

  return (
    <div className="app">
      {view === "login" ? (
        <Login
          username={username} pw={pw} remember={remember}
          setUsername={setUsername} setPw={setPw} setRemember={setRemember}
          error={error} busy={busy}
          onSubmit={handleLogin}
        />
      ) : (
        <Home
          menuOpen={menuOpen} setMenuOpen={setMenuOpen}
          active={active} setActive={setActive}
          apps={apps}
          onLogout={handleLogout}
        />
      )}
    </div>
  );
}

function Login({ username, pw, remember, setUsername, setPw, setRemember, error, busy, onSubmit }) {
  const submit = (e) => { e.preventDefault(); onSubmit(); };
  return (
    <div className="login" data-screen-label="01 Login">
      <div className="login__inner">
        <div className="brand">
          <div className="brand__mark"><Logo size={22} /></div>
          <div className="brand__name">{BRAND}</div>
        </div>

        <div className="login__head">
          <div className="eyebrow">Inloggning</div>
          <h1 className="login__title">Välkommen.</h1>
          <p className="login__sub">{TAGLINE}</p>
        </div>

        <form className="form" onSubmit={submit}>
          <label className="field">
            <span className="field__label">Användarnamn</span>
            <input
              type="text" value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="Användare" autoComplete="username" required
            />
          </label>

          <label className="field">
            <span className="field__label">
              Lösenord
              <a href="#" className="field__aux" onClick={(e) => e.preventDefault()}>Glömt?</a>
            </span>
            <input
              type="password" value={pw}
              onChange={(e) => setPw(e.target.value)}
              placeholder="••••••••" autoComplete="current-password" required
            />
          </label>

          <label className="check">
            <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
            <span className="check__box" aria-hidden="true">
              <svg viewBox="0 0 12 12" width="10" height="10" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <path d="M2 6.5 L5 9 L10 3" />
              </svg>
            </span>
            <span className="check__label">Kom ihåg mig</span>
          </label>

          <button type="submit" className="btn btn--primary" disabled={busy}>
            {busy ? "Loggar in\u2026" : "Logga in"}
          </button>

          {error && <div className="form__error" role="alert">{error}</div>}
        </form>
      </div>

      <div className="login__legal">© {BRAND} 2026 · v0.4 · Sekretess · Villkor</div>
    </div>
  );
}

function Home({ menuOpen, setMenuOpen, active, setActive, apps, onLogout }) {
  // apps === null   → preview/demo (servern svarade inte) — visa allt
  // apps === ["*"]  → super-user — visa allt
  // apps === [...]  → explicit lista — visa bara matchande id:n
  const visibleItems = (apps == null || apps.includes("*"))
    ? MENU_ITEMS
    : MENU_ITEMS.filter((it) => apps.includes(it.id));
  return (
    <div className="home" data-screen-label="02 Startsida">
      <header className="top">
        <button className={"hbtn " + (menuOpen ? "is-open" : "")} aria-label="Meny" onClick={() => setMenuOpen((v) => !v)}>
          <span></span><span></span><span></span>
        </button>
        <div className="brand brand--top">
          <div className="brand__mark"><Logo size={18} /></div>
          <div className="brand__name">{BRAND}</div>
        </div>
        <button className="avatar" aria-label="Konto" onClick={onLogout} title="Logga ut">
          <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <circle cx="12" cy="8" r="3.5" />
            <path d="M4.5 20c1.2-3.6 4.3-5.5 7.5-5.5s6.3 1.9 7.5 5.5" />
          </svg>
        </button>
      </header>

      <main className="stage">
        <div className="hello">
          <div className="eyebrow">Tisdag 19 maj · 14:02</div>
          <h2 className="hello__title">Var god välj verktyg.</h2>
          <button className="hello__cta" onClick={() => setMenuOpen(true)}>
            <span>Öppna meny</span>
            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 12 H19 M13 6 L19 12 L13 18" /></svg>
          </button>
        </div>
      </main>

      <div className={"scrim " + (menuOpen ? "is-on" : "")} onClick={() => setMenuOpen(false)} />

      <aside className={"menu " + (menuOpen ? "is-open" : "")} aria-hidden={!menuOpen}>
        <div className="menu__head">
          <div className="menu__eyebrow">Verktyg · {visibleItems.length}</div>
          <button className="menu__close" aria-label="Stäng meny" onClick={() => setMenuOpen(false)}>
            <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 5 L19 19 M19 5 L5 19" /></svg>
          </button>
        </div>

        <ul className="menu__list">
          {visibleItems.map((it, i) => (
            <li key={it.id} style={{ "--i": i }}>
              {it.href ? (
                <a className="menu__item" href={it.href}>
                  <span className="menu__num">{String(i + 1).padStart(2, "0")}</span>
                  <span className="menu__body">
                    <span className="menu__label">{it.label}</span>
                    <span className="menu__hint">{it.hint}</span>
                  </span>
                  <span className="menu__arrow">
                    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 12 H19 M13 6 L19 12 L13 18" /></svg>
                  </span>
                </a>
              ) : (
                <button
                  className="menu__item"
                  onClick={() => { setActive({ ...it, soon: true }); setMenuOpen(false); }}
                >
                  <span className="menu__num">{String(i + 1).padStart(2, "0")}</span>
                  <span className="menu__body">
                    <span className="menu__label">{it.label}</span>
                    <span className="menu__hint">{it.hint}</span>
                  </span>
                  <span className="menu__arrow menu__arrow--soon">Kommer snart</span>
                </button>
              )}
            </li>
          ))}
        </ul>

        <div className="menu__foot">
          <button className="menu__foot-item" onClick={onLogout}>Logga ut</button>
          <span className="menu__foot-meta">v0.4</span>
        </div>
      </aside>

      {active && (
        <div className="toast">
          <div className="toast__title">{active.label}</div>
          <div className="toast__sub">{active.soon ? "\u00d6ppnar inte \u00e4n \u2014 verktyget kommer snart." : active.hint}</div>
          <button className="toast__x" onClick={() => setActive(null)} aria-label="St\u00e4ng">×</button>
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
