/* CRM main app — composes shell + views, handles routing + tweaks */
const { useState: useApp, useEffect: useApe } = React;

// ─── Login screen ─────────────────────────────────────────────────────────────
function LoginScreen({ onLogin }) {
  const [username, setUsername] = useApp("");
  const [password, setPassword] = useApp("");
  const [error, setError]       = useApp("");
  const [loading, setLoading]   = useApp(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      const res = await fetch("/api/auth/login/", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({ username, password }),
      });
      const data = await res.json();
      if (res.ok) {
        window.ArisAuth.setToken(data.token, data.username, data.role);
        onLogin();
      } else {
        setError(data.error || "Login failed.");
      }
    } catch (err) {
      setError("Cannot reach server. Check your connection.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center",
      background: "var(--paper)", fontFamily: "var(--font-sans)",
    }}>
      <div style={{
        position: "fixed", inset: 0, opacity: 0.03, pointerEvents: "none",
        backgroundImage: "repeating-linear-gradient(0deg, var(--ink) 0px, var(--ink) 1px, transparent 1px, transparent 40px), repeating-linear-gradient(90deg, var(--ink) 0px, var(--ink) 1px, transparent 1px, transparent 40px)",
      }} />

      <div style={{ width: 360, position: "relative", zIndex: 1 }}>
        <div style={{ textAlign: "center", marginBottom: 40 }}>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 10,
            fontFamily: "var(--font-serif)", fontSize: 28, fontWeight: 400,
            letterSpacing: "-0.02em", color: "var(--ink)",
          }}>
            <LogoMark size={32} />
            <span>Aris</span>
          </div>
          <div style={{
            marginTop: 6, fontFamily: "var(--font-mono)", fontSize: 10,
            letterSpacing: "0.18em", color: "var(--fog)", textTransform: "uppercase",
          }}>
            Operations Console
          </div>
        </div>

        <form onSubmit={handleSubmit} style={{
          background: "var(--surface)", border: "1px solid var(--rule)",
          borderRadius: 2, padding: "32px 32px 28px",
        }}>
          <div style={{
            fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em",
            color: "var(--fog)", textTransform: "uppercase", marginBottom: 24,
          }}>
            Auth / Sign in
          </div>

          <div style={{ marginBottom: 16 }}>
            <label style={{
              display: "block", fontFamily: "var(--font-mono)", fontSize: 9,
              letterSpacing: "0.14em", color: "var(--ink-2)", textTransform: "uppercase",
              marginBottom: 6,
            }}>Username</label>
            <input
              type="text" value={username} autoComplete="username"
              onChange={e => setUsername(e.target.value)} required
              style={{
                width: "100%", padding: "10px 12px", boxSizing: "border-box",
                background: "var(--paper)", border: "1px solid var(--rule)",
                borderRadius: 1, color: "var(--ink)",
                fontFamily: "var(--font-mono)", fontSize: 13, outline: "none",
              }}
            />
          </div>

          <div style={{ marginBottom: 24 }}>
            <label style={{
              display: "block", fontFamily: "var(--font-mono)", fontSize: 9,
              letterSpacing: "0.14em", color: "var(--ink-2)", textTransform: "uppercase",
              marginBottom: 6,
            }}>Password</label>
            <input
              type="password" value={password} autoComplete="current-password"
              onChange={e => setPassword(e.target.value)} required
              style={{
                width: "100%", padding: "10px 12px", boxSizing: "border-box",
                background: "var(--paper)", border: "1px solid var(--rule)",
                borderRadius: 1, color: "var(--ink)",
                fontFamily: "var(--font-mono)", fontSize: 13, outline: "none",
              }}
            />
          </div>

          {error && (
            <div style={{
              marginBottom: 16, padding: "8px 12px",
              background: "rgba(220,50,50,0.08)", border: "1px solid rgba(220,50,50,0.3)",
              borderRadius: 1, fontFamily: "var(--font-mono)", fontSize: 11, color: "#e05555",
            }}>
              {error}
            </div>
          )}

          <button type="submit" disabled={loading} style={{
            width: "100%", padding: "10px 0",
            background: loading ? "var(--fog)" : "var(--accent)",
            border: "none", borderRadius: 1, cursor: loading ? "wait" : "pointer",
            fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600,
            letterSpacing: "0.12em", textTransform: "uppercase",
            color: "var(--paper)", transition: "opacity 0.15s",
          }}>
            {loading ? "Signing in..." : "Sign in"}
          </button>
        </form>

        <div style={{
          marginTop: 16, textAlign: "center",
          fontFamily: "var(--font-mono)", fontSize: 9,
          letterSpacing: "0.12em", color: "var(--fog)", textTransform: "uppercase",
        }}>
          Aris Operations Console · Internal use only
        </div>
      </div>
    </div>
  );
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "moss",
  "density": "spacious"
}/*EDITMODE-END*/;

function PlaceholderView({ title, num }) {
  return (
    <div style={{paddingTop:80, textAlign:"center"}}>
      <div className="coord" style={{marginBottom:12}}>§ {num} / {title.toUpperCase()}</div>
      <h1 style={{fontFamily:"var(--font-serif)", fontSize:48, fontWeight:400, letterSpacing:"-0.02em"}}>
        {title} · <em style={{fontStyle:"italic", color:"var(--accent)", fontWeight:300}}>coming soon</em>
      </h1>
      <p style={{maxWidth:"42ch", margin:"24px auto 0", color:"var(--ink-2)", fontSize:15}}>
        This module is part of the next milestone. Head to the Agents Hub or Dashboard for now.
      </p>
    </div>
  );
}

function App({ onLogout }) {
  const [view, setView] = useApp("agents");
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useApe(() => {
    document.body.classList.add("crm-body");
    return () => document.body.classList.remove("crm-body");
  }, []);

  useApe(() => {
    document.body.classList.remove("accent-moss", "accent-ochre", "accent-ink");
    document.body.classList.add(`accent-${tweaks.accent}`);
  }, [tweaks.accent]);

  useApe(() => {
    document.body.classList.remove("density-spacious", "density-balanced", "density-dense");
    document.body.classList.add(`density-${tweaks.density}`);
  }, [tweaks.density]);

  const renderView = () => {
    switch (view) {
      case "agents":    return <AgentsHub />;
      case "dashboard": return <Dashboard />;
      case "leads":     return <Leads />;
      case "deals":     return <PlaceholderView title="Deals" num="02.02" />;
      case "pipeline":  return <PlaceholderView title="Pipeline" num="02.03" />;
      case "people":    return <Customers />;
      case "tasks":     return <TaskChat />;
      case "users":     return <UserManagement />;
      case "settings":  return <PlaceholderView title="Settings" num="03.01" />;
      default:          return <AgentsHub />;
    }
  };

  return (
    <>
      <div className="console">
        <TopBar />
        <Sidebar active={view} onChange={setView} />
        <main className="canvas">
          <ContourDeco />
          <div className="canvas-inner">
            {renderView()}
          </div>
        </main>
        <StatusBar view={view} />
      </div>

      <button
        onClick={onLogout}
        title={`Signed in as ${window.ArisAuth.getUsername()} · Click to sign out`}
        style={{
          position: "fixed", top: 12, right: 16, zIndex: 9999,
          background: "none", border: "1px solid var(--rule)",
          borderRadius: 1, padding: "4px 10px", cursor: "pointer",
          fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.12em",
          textTransform: "uppercase", color: "var(--fog)",
          transition: "color 0.15s, border-color 0.15s",
        }}
        onMouseEnter={e => { e.target.style.color = "var(--ink)"; e.target.style.borderColor = "var(--ink-2)"; }}
        onMouseLeave={e => { e.target.style.color = "var(--fog)"; e.target.style.borderColor = "var(--rule)"; }}
      >
        {window.ArisAuth.getUsername()} · out
      </button>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Theme">
          <TweakRadio label="Accent" value={tweaks.accent} onChange={(v) => setTweak("accent", v)}
            options={[{value:"moss",label:"Moss"},{value:"ochre",label:"Ochre"},{value:"ink",label:"Ink"}]} />
          <TweakRadio label="Density" value={tweaks.density} onChange={(v) => setTweak("density", v)}
            options={[{value:"spacious",label:"Spacious"},{value:"balanced",label:"Balanced"},{value:"dense",label:"Dense"}]} />
        </TweakSection>
        <TweakSection label="Navigation">
          <TweakRadio label="View" value={view} onChange={(v) => setView(v)}
            options={[{value:"agents",label:"Agents"},{value:"dashboard",label:"Dashboard"},{value:"tasks",label:"Tasks"},{value:"people",label:"Customers"}]} />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

// ─── Root — auth gate ─────────────────────────────────────────────────────────
function Root() {
  const [loggedIn, setLoggedIn] = useApp(window.ArisAuth.isLoggedIn());

  const handleLogin = () => setLoggedIn(true);

  const handleLogout = async () => {
    try { await fetch("/api/auth/logout/", { method: "POST" }); } catch (_) {}
    window.ArisAuth.clearToken();
    setLoggedIn(false);
  };

  if (!loggedIn) return <LoginScreen onLogin={handleLogin} />;
  return <App onLogout={handleLogout} />;
}

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