/* ============================================================
   Media SOP — Supabase Auth (login, register, session)
   ============================================================ */

// ---- Supabase client ----
const SUPA_URL  = "https://wymfmkufzfrrjztulqvs.supabase.co";
const SUPA_ANON = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Ind5bWZta3VmemZycmp6dHVscXZzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODA0NzgwOTgsImV4cCI6MjA5NjA1NDA5OH0.lt0tLxSCcPBsaix6lTCNJdpLpBxcGptj4Ve5syWxEzY";
const supabase  = window.supabase.createClient(SUPA_URL, SUPA_ANON);
window.supabase_client = supabase;

// ---- Role config ----
const ROLE_OPTIONS = [
  {
    value: "order",
    label: "Người Order",
    desc: "Gửi yêu cầu sản xuất, theo dõi & nghiệm thu sản phẩm",
    icon: "📋",
    color: "oklch(0.55 0.18 250)",
  },
  {
    value: "editor",
    label: "Editor",
    desc: "Nhận việc, cập nhật tiến độ, xem KPI cá nhân",
    icon: "🎬",
    color: "oklch(0.55 0.20 290)",
  },
  {
    value: "manager",
    label: "Quản lý",
    desc: "Tiếp nhận order, điều phối team, xem dashboard tổng",
    icon: "📊",
    color: "oklch(0.50 0.22 320)",
  },
];

const DEPT_OPTIONS = ["Marketing", "Media", "Creative", "Sales", "HR", "Khác"];

// ---- AuthGate: bọc toàn app, kiểm tra session ----
function AuthGate({ children }) {
  const [session, setSession]   = React.useState(undefined); // undefined = đang load
  const [profile, setProfile]   = React.useState(null);
  const [authMode, setAuthMode] = React.useState("login");   // "login" | "register"

  // Lấy session khi mount
  React.useEffect(() => {
    supabase.auth.getSession().then(({ data }) => {
      setSession(data.session);
      if (data.session) fetchProfile(data.session.user.id);
    });
    const { data: listener } = supabase.auth.onAuthStateChange((_e, sess) => {
      setSession(sess);
      if (sess) fetchProfile(sess.user.id);
      else setProfile(null);
    });
    return () => listener.subscription.unsubscribe();
  }, []);

  async function fetchProfile(uid) {
    const { data } = await supabase.from("profiles").select("*").eq("id", uid).maybeSingle();
    setProfile(data); // null nếu chưa có → hiện CompleteProfile
  }

  // Đang kiểm tra session
  if (session === undefined) return (
    <div style={{ height: "100vh", display: "grid", placeItems: "center", background: "var(--bg)" }}>
      <div style={{ textAlign: "center", color: "oklch(0.65 0.05 290)" }}>
        <div style={{ fontSize: 32, marginBottom: 12 }}>🎬</div>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 18 }}>Media SOP</div>
        <div style={{ fontSize: 13, marginTop: 6, opacity: 0.6 }}>Đang kết nối...</div>
      </div>
    </div>
  );

  // Chưa đăng nhập
  if (!session) return authMode === "login"
    ? <LoginScreen onSwitch={() => setAuthMode("register")} />
    : <RegisterScreen onSwitch={() => setAuthMode("login")} />;

  // Đã đăng nhập nhưng chưa có profile (lần đầu)
  if (!profile) return <CompleteProfile user={session.user} onDone={fetchProfile} />;

  // Đã đăng nhập + có profile → render app
  return React.cloneElement(children, { supabaseUser: session.user, supabaseProfile: profile });
}

window.AuthGate   = AuthGate;
window.supabaseClient = supabase;


// ---- LoginScreen ----
function LoginScreen({ onSwitch }) {
  const [email, setEmail]     = React.useState("");
  const [password, setPass]   = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError]     = React.useState("");

  async function handleLogin(e) {
    e.preventDefault();
    setLoading(true); setError("");
    const { error } = await supabase.auth.signInWithPassword({ email, password });
    if (error) setError(error.message);
    setLoading(false);
  }

  return (
    <div className="auth-bg">
      <div className="auth-card">
        {/* Logo */}
        <div className="auth-logo">
          <div className="brand-mark" style={{ width: 48, height: 48, borderRadius: 14, fontSize: 22 }}>🎬</div>
          <div>
            <div className="auth-title">Media SOP</div>
            <div className="auth-sub">Quy trình sản xuất media</div>
          </div>
        </div>

        <h2 className="auth-heading">Đăng nhập</h2>

        <form onSubmit={handleLogin} className="auth-form">
          <label className="auth-label">Email</label>
          <input
            className="auth-input"
            type="email" placeholder="ten@company.com"
            value={email} onChange={e => setEmail(e.target.value)}
            required autoFocus
          />
          <label className="auth-label">Mật khẩu</label>
          <input
            className="auth-input"
            type="password" placeholder="••••••••"
            value={password} onChange={e => setPass(e.target.value)}
            required
          />
          {error && <div className="auth-error">{error}</div>}
          <button className="auth-btn" type="submit" disabled={loading}>
            {loading ? "Đang đăng nhập..." : "Đăng nhập"}
          </button>
        </form>

        <div className="auth-footer">
          Chưa có tài khoản?{" "}
          <button className="auth-link" onClick={onSwitch}>Đăng ký ngay</button>
        </div>
      </div>
    </div>
  );
}

// ---- RegisterScreen ----
function RegisterScreen({ onSwitch }) {
  const [step, setStep]       = React.useState(1); // 1 = thông tin, 2 = chọn role
  const [email, setEmail]     = React.useState("");
  const [password, setPass]   = React.useState("");
  const [name, setName]       = React.useState("");
  const [dept, setDept]       = React.useState("Marketing");
  const [role, setRole]       = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [error, setError]     = React.useState("");
  const [done, setDone]       = React.useState(false);

  async function handleRegister() {
    setLoading(true); setError("");
    const { data, error: signupErr } = await supabase.auth.signUp({ email, password });
    if (signupErr) { setError(signupErr.message); setLoading(false); return; }

    if (data.user) {
      const { error: profileErr } = await supabase.from("profiles").insert({
        id: data.user.id, name, role, dept,
      });
      if (profileErr) { setError(profileErr.message); setLoading(false); return; }
    }
    setLoading(false);
    setDone(true);
  }

  if (done) return (
    <div className="auth-bg">
      <div className="auth-card" style={{ textAlign: "center" }}>
        <div style={{ fontSize: 48, marginBottom: 12 }}>✅</div>
        <h2 className="auth-heading">Đăng ký thành công!</h2>
        <p style={{ color: "oklch(0.65 0.05 290)", fontSize: 14, lineHeight: 1.6 }}>
          Kiểm tra email <b>{email}</b> để xác nhận tài khoản, sau đó đăng nhập.
        </p>
        <button className="auth-btn" style={{ marginTop: 20 }} onClick={onSwitch}>Đến trang đăng nhập</button>
      </div>
    </div>
  );

  return (
    <div className="auth-bg">
      <div className="auth-card">
        <div className="auth-logo">
          <div className="brand-mark" style={{ width: 48, height: 48, borderRadius: 14, fontSize: 22 }}>🎬</div>
          <div>
            <div className="auth-title">Media SOP</div>
            <div className="auth-sub">Tạo tài khoản mới</div>
          </div>
        </div>

        {/* Step indicator */}
        <div className="auth-steps">
          <div className={"auth-step" + (step >= 1 ? " active" : "")}>1 Thông tin</div>
          <div className="auth-step-line" />
          <div className={"auth-step" + (step >= 2 ? " active" : "")}>2 Vai trò</div>
        </div>

        {step === 1 && (
          <div className="auth-form">
            <label className="auth-label">Họ tên</label>
            <input className="auth-input" type="text" placeholder="Nguyễn Văn A"
              value={name} onChange={e => setName(e.target.value)} autoFocus />

            <label className="auth-label">Email</label>
            <input className="auth-input" type="email" placeholder="ten@company.com"
              value={email} onChange={e => setEmail(e.target.value)} />

            <label className="auth-label">Mật khẩu</label>
            <input className="auth-input" type="password" placeholder="Tối thiểu 6 ký tự"
              value={password} onChange={e => setPass(e.target.value)} />

            <label className="auth-label">Phòng ban</label>
            <select className="auth-input auth-select" value={dept} onChange={e => setDept(e.target.value)}>
              {DEPT_OPTIONS.map(d => <option key={d} value={d}>{d}</option>)}
            </select>

            {error && <div className="auth-error">{error}</div>}
            <button className="auth-btn" onClick={() => {
              if (!name || !email || !password) { setError("Vui lòng điền đầy đủ thông tin."); return; }
              if (password.length < 6) { setError("Mật khẩu phải có ít nhất 6 ký tự."); return; }
              setError(""); setStep(2);
            }}>Tiếp theo →</button>
          </div>
        )}

        {step === 2 && (
          <div className="auth-form">
            <p className="auth-label" style={{ marginBottom: 12 }}>Bạn sẽ dùng hệ thống với vai trò nào?</p>
            <div className="role-picker">
              {ROLE_OPTIONS.map(r => (
                <button
                  key={r.value}
                  className={"role-card" + (role === r.value ? " selected" : "")}
                  onClick={() => setRole(r.value)}
                  style={{ "--role-color": r.color }}
                >
                  <span className="role-card-icon">{r.icon}</span>
                  <div className="role-card-label">{r.label}</div>
                  <div className="role-card-desc">{r.desc}</div>
                </button>
              ))}
            </div>
            {error && <div className="auth-error">{error}</div>}
            <div className="row" style={{ gap: 10 }}>
              <button className="auth-btn-outline" onClick={() => { setStep(1); setError(""); }}>← Quay lại</button>
              <button className="auth-btn" style={{ flex: 1 }} disabled={!role || loading} onClick={() => {
                if (!role) { setError("Vui lòng chọn vai trò."); return; }
                handleRegister();
              }}>
                {loading ? "Đang tạo tài khoản..." : "Hoàn tất đăng ký"}
              </button>
            </div>
          </div>
        )}

        <div className="auth-footer">
          Đã có tài khoản?{" "}
          <button className="auth-link" onClick={onSwitch}>Đăng nhập</button>
        </div>
      </div>
    </div>
  );
}

// ---- CompleteProfile: hiện khi user đã đăng ký nhưng chưa có profile ----
function CompleteProfile({ user, onDone }) {
  const [name, setName]   = React.useState("");
  const [role, setRole]   = React.useState("");
  const [dept, setDept]   = React.useState("Marketing");
  const [loading, setLoad] = React.useState(false);
  const [error, setError] = React.useState("");

  async function save() {
    if (!name || !role) { setError("Vui lòng điền tên và chọn vai trò."); return; }
    setLoad(true);
    const { error } = await supabase.from("profiles").upsert({ id: user.id, name, role, dept });
    if (error) setError(error.message);
    else onDone(user.id);
    setLoad(false);
  }

  return (
    <div className="auth-bg">
      <div className="auth-card">
        <div className="auth-logo">
          <div className="brand-mark" style={{ width: 48, height: 48, borderRadius: 14, fontSize: 22 }}>🎬</div>
          <div><div className="auth-title">Hoàn thiện hồ sơ</div></div>
        </div>
        <div className="auth-form">
          <label className="auth-label">Họ tên</label>
          <input className="auth-input" type="text" placeholder="Nguyễn Văn A"
            value={name} onChange={e => setName(e.target.value)} autoFocus />
          <label className="auth-label">Phòng ban</label>
          <select className="auth-input auth-select" value={dept} onChange={e => setDept(e.target.value)}>
            {DEPT_OPTIONS.map(d => <option key={d} value={d}>{d}</option>)}
          </select>
          <p className="auth-label" style={{ marginBottom: 12, marginTop: 8 }}>Vai trò của bạn</p>
          <div className="role-picker">
            {ROLE_OPTIONS.map(r => (
              <button key={r.value} className={"role-card" + (role === r.value ? " selected" : "")}
                onClick={() => setRole(r.value)} style={{ "--role-color": r.color }}>
                <span className="role-card-icon">{r.icon}</span>
                <div className="role-card-label">{r.label}</div>
                <div className="role-card-desc">{r.desc}</div>
              </button>
            ))}
          </div>
          {error && <div className="auth-error">{error}</div>}
          <button className="auth-btn" disabled={loading} onClick={save}>
            {loading ? "Đang lưu..." : "Bắt đầu sử dụng →"}
          </button>
        </div>
      </div>
    </div>
  );
}
