// modals.jsx — JobDetail, Auth, AdminEdit/Add

// ============== Job Detail ==============
const JobDetailModal = ({ job, onClose, onSave, isSaved, onApply }) => {
  if (!job) return null;
  const country = window.COUNTRIES.find(c => c.code === job.country);
  const fresh = window.freshnessFromDate(job.verifiedDate);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal modal-lg" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head" style={{background: "linear-gradient(180deg, var(--paper) 0%, var(--white) 100%)", padding: "26px 32px"}}>
          <div style={{display:"flex", gap: 16, alignItems:"flex-start", flex: 1}}>
            <div style={{width: 56, height: 56, borderRadius: 8, background:"var(--paper-2)", display:"grid", placeItems:"center", fontFamily:"var(--f-display)", fontSize: 26, color:"var(--navy-800)", flex: "none"}}>
              {job.companyLogo}
            </div>
            <div style={{flex: 1}}>
              <div style={{display:"flex", gap:8, marginBottom: 8, flexWrap:"wrap"}}>
                <FreshnessPill level={fresh}/>
                {job.visa.verified && <VerifiedBadge/>}
                <span className="badge badge-navy">{job.visa.type}</span>
              </div>
              <h3 style={{fontFamily:"var(--f-display)", fontSize: 28, margin: 0, letterSpacing:"-0.01em"}}>{job.title}</h3>
              <div style={{color:"var(--ink-3)", marginTop: 4, fontSize: 14}}>
                <b style={{color:"var(--ink)", fontWeight: 500}}>{job.company}</b> · <span>{country?.flag} {job.city}, {country?.name}</span> · <span>{job.industry}</span>
              </div>
            </div>
          </div>
          <button className="btn-icon" onClick={onClose}><Icon name="cross" size={16}/></button>
        </div>

        <div className="modal-body">
          {/* Key facts grid */}
          <div style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap: 12, marginBottom: 24}}>
            {[
              { lbl: "Salary", val: window.fmtSalary(job.salaryMin, job.salaryMax, job.currency), sub: window.fmtSalary(job.salaryMin, job.salaryMax, job.currency) === "Not Disclosed" ? "" : "per year" },
              { lbl: "Visa type", val: job.visa.type, sub: job.visa.sponsorshipType },
              { lbl: "Experience", val: job.experience, sub: job.collar + " collar" },
              { lbl: "Verified", val: job.verifiedDate, sub: `${Math.floor((Date.now() - new Date(job.verifiedDate).getTime()) / 86400000)} days ago` },
            ].map((f, i) => (
              <div key={i} style={{padding: 14, background: "var(--paper)", borderRadius: 8, border: "1px solid var(--line)"}}>
                <div className="col-label">{f.lbl}</div>
                <div style={{fontFamily:"var(--f-display)", fontSize: 18, letterSpacing:"-0.01em", color:"var(--navy-900)"}}>{f.val}</div>
                <div style={{fontSize: 11, color:"var(--ink-3)", marginTop: 2, textTransform:"capitalize"}}>{f.sub}</div>
              </div>
            ))}
          </div>

          {/* Trust signals strip */}
          <div style={{display:"grid", gridTemplateColumns:"repeat(3, 1fr)", gap: 8, marginBottom: 24, padding: 14, background:"var(--navy-50)", borderRadius: 8, border:"1px solid var(--navy-100)"}}>
            <div style={{display:"flex", gap: 10, alignItems:"center"}}>
              <span className={`chip ${job.ielts ? "on" : "off"}`} style={{height: 26}}>
                <Icon name={job.ielts ? "check" : "cross"} size={12}/> IELTS {job.ielts ? "required" : "not required"}
              </span>
            </div>
            <div style={{display:"flex", gap:10, alignItems:"center"}}>
              <span className={`chip ${job.pr ? "on" : "off"}`} style={{height: 26}}>
                <Icon name={job.pr ? "check" : "cross"} size={12}/> PR pathway {job.pr ? "available" : "n/a"}
              </span>
            </div>
            <div style={{display:"flex", gap:10, alignItems:"center"}}>
              <span className="chip on" style={{height: 26}}>
                <Icon name="shield" size={12}/> Sponsor licence on file
              </span>
            </div>
          </div>

          {/* Description */}
          <div style={{marginBottom: 24}}>
            <h4 className="serif" style={{fontSize: 18, margin: "0 0 8px"}}>About the role</h4>
            <p style={{color:"var(--ink-2)", lineHeight: 1.6, margin: 0}}>{job.description}</p>
          </div>

          <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap: 28}}>
            <div>
              <h4 className="serif" style={{fontSize: 18, margin: "0 0 10px"}}>Requirements</h4>
              <ul style={{margin: 0, padding: 0, listStyle:"none"}}>
                {job.requirements.map((r, i) => (
                  <li key={i} style={{display:"flex", gap: 10, padding: "6px 0", color:"var(--ink-2)"}}>
                    <Icon name="check" size={14} stroke={2}/> <span>{r}</span>
                  </li>
                ))}
              </ul>
            </div>
            <div>
              <h4 className="serif" style={{fontSize: 18, margin: "0 0 10px"}}>Visa & benefits</h4>
              <ul style={{margin: 0, padding: 0, listStyle:"none"}}>
                {job.benefits.map((r, i) => (
                  <li key={i} style={{display:"flex", gap: 10, padding: "6px 0", color:"var(--ink-2)"}}>
                    <Icon name="star" size={14} stroke={2} /> <span>{r}</span>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>

        <div className="modal-foot">
          <button className="btn btn-ghost" onClick={() => onSave?.(job)}>
            <Icon name="bookmark" size={14}/> {isSaved ? "Saved to shortlist" : "Save job"}
          </button>
          <button className="btn btn-dark">Share role</button>
          <button className="btn btn-primary" onClick={() => onApply(job)}>Apply now <Icon name="arrowRight" size={14}/></button>
        </div>
      </div>
    </div>
  );
};

// ============== Auth Modal ==============
const AuthModal = ({ onClose, onAuth }) => {
  const [mode, setMode] = React.useState("signup"); // signup | signin | forgot
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [showPassword, setShowPassword] = React.useState(false);
  const [err, setErr] = React.useState("");

  const [message, setMessage] = React.useState(null); // { title, body, icon, type }


  const submit = async (e) => {
    e.preventDefault();
    if (mode !== "forgot" && (!email || !password)) { setErr("Email and password required"); return; }
    if (mode === "signup" && !name) { setErr("Name is required"); return; }
    if (mode === "forgot" && !email) { setErr("Email is required"); return; }
    setErr("");
    
    if (mode === "signup") {
      const res = await window.signUp(email, password, name);
      if (res.error) {
        if (res.error.includes("already-in-use") || res.error.includes("already registered")) {
          setMessage({
            title: "Email already registered",
            body: "This email is already associated with an account. Please sign in instead.",
            icon: "bell",
            type: "warning",
            onAction: () => { setMessage(null); setMode("signin"); }
          });
        } else {
          setErr(res.error);
        }
      } else if (res.success) {
        setMessage({
          title: "Verify your email",
          body: `We've sent a verification link to ${email}. Please check your inbox (and spam folder) to activate your account.`,
          icon: "sparkle",
          type: "success",
          onAction: () => { 
            setMessage(null); 
            setMode("signin"); 
            // We keep email and password states as they are
          }
        });
      }
    } else if (mode === "signin") {

      const res = await window.signIn(email, password);
      if (res.error === "VERIFY_EMAIL") {
        setMessage({
          title: "Account not verified",
          body: "Please verify your email address before signing in. Check your inbox for the verification link.",
          icon: "bell",
          type: "warning",
          onAction: async () => {
            await window.sendVerificationEmail();
            setMessage({ ...message, body: "A new verification link has been sent. Please check your email." });
          }
        });
      } else if (res.error) {
        setErr(res.error);
      } else {
        onAuth(res.user);
      }
    } else if (mode === "forgot") {
      const res = await window.sendPasswordReset(email);
      if (res.error) {
        setErr(res.error);
      } else {
        setMessage({
          title: "Reset link sent",
          body: `A password reset link has been sent to ${email}. Please check your inbox.`,
          icon: "check",
          type: "success",
          onAction: () => { setMessage(null); setMode("signin"); }
        });
      }
    }
  };


  if (message) {
    return <MessageModal 
      title={message.title} 
      body={message.body} 
      icon={message.icon} 
      type={message.type} 
      onAction={message.onAction} 
      onClose={() => setMessage(null)} 
    />;
  }

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal modal-sm" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head" style={{borderBottom: 0, paddingBottom: 0}}>
          <div>
            <div className="eyebrow" style={{color:"var(--gold-700)", marginBottom: 4}}><span className="bar"></span> GYD account</div>
            <h3>
              {mode === "signup" ? "Create your account" : 
               mode === "signin" ? "Welcome back" : "Reset password"}
            </h3>
          </div>
          <button className="btn-icon" onClick={onClose}><Icon name="cross" size={16}/></button>
        </div>
        <form onSubmit={submit} className="modal-body" style={{paddingTop: 6}}>
          <p style={{color:"var(--ink-3)", marginTop: 0, marginBottom: 18}}>
            {mode === "signup" ? "Free — no credit card required. Save jobs, get verification alerts." : 
             mode === "signin" ? "Sign in to access your shortlist and applications." :
             "Enter your email address and we'll send you a link to reset your password."}
          </p>
          
          {mode === "signup" && (
            <div style={{marginBottom: 14}}>
              <label className="label">Full name</label>
              <input className="input" placeholder="Aanya Sharma" value={name} onChange={(e) => setName(e.target.value)} />
            </div>
          )}

          <div style={{marginBottom: 14}}>
            <label className="label">Email</label>
            <input className="input" type="email" placeholder="you@example.com" value={email} onChange={(e) => setEmail(e.target.value)} />
          </div>

          {mode !== "forgot" && (
            <div style={{marginBottom: 6}}>
              <label className="label">Password</label>
              <div style={{position: "relative"}}>
                <input 
                  className="input" 
                  type={showPassword ? "text" : "password"} 
                  placeholder="••••••••" 
                  value={password} 
                  onChange={(e) => setPassword(e.target.value)} 
                  style={{paddingRight: 40}}
                />
                <button 
                  type="button" 
                  onClick={() => setShowPassword(!showPassword)}
                  style={{
                    position: "absolute",
                    right: 8,
                    top: "50%",
                    transform: "translateY(-50%)",
                    background: "none",
                    border: "none",
                    padding: 8,
                    color: "var(--ink-4)",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    cursor: "pointer"
                  }}
                >
                  <Icon name={showPassword ? "eye" : "eyeOff"} size={16} />
                </button>
              </div>
            </div>
          )}

          {mode === "signin" && (
            <div style={{textAlign: "right", marginBottom: 14}}>
              <button type="button" className="btn-link" style={{fontSize: 12}} onClick={() => setMode("forgot")}>
                Forgot password?
              </button>
            </div>
          )}

          {err && <div style={{color:"var(--danger)", fontSize: 12, marginTop: 8}}>{err}</div>}
          
          <button type="submit" className="btn btn-primary btn-lg" style={{width: "100%", marginTop: 18}}>
            {mode === "signup" ? "Create account" : 
             mode === "signin" ? "Sign in" : "Send reset link"}
          </button>

          <div style={{textAlign:"center", color:"var(--ink-3)", marginTop: 14, fontSize: 13}}>
            {mode === "signup" ? "Already a member?" : (mode === "signin" ? "New to GYD?" : "Back to")}
            {" "}
            <button type="button" className="btn-link" onClick={() => setMode(mode === "signup" ? "signin" : (mode === "signin" ? "signup" : "signin"))}>
              {mode === "signup" ? "Sign in" : (mode === "signin" ? "Create account" : "Sign in")}
            </button>
          </div>

          {mode !== "forgot" && (
            <>
              <div style={{display:"flex", alignItems:"center", gap: 10, margin: "20px 0"}}>
                <div style={{flex:1, height: 1, background: "var(--line)"}}></div>
                <span style={{fontSize: 12, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.05em"}}>or continue with</span>
                <div style={{flex:1, height: 1, background: "var(--line)"}}></div>
              </div>

              <button
                type="button"
                className="btn btn-ghost"
                style={{width: "100%", height: 48, borderColor: "#e5e7eb", background: "#fff"}}
                onClick={async () => {
                  const res = await window.signInWithGoogle();
                  if (res.error) setErr(res.error);
                  else onAuth(res.user);
                }}
              >
                <Icon name="google" size={18} />
                Continue with Google
              </button>
            </>
          )}
        </form>
      </div>
    </div>
  );
};




// ============== Apply Modal ==============
const ApplyModal = ({ job, onClose }) => {
  if (!job) return null;

  const handleApply = () => {
    if (job.applyUrl && job.applyUrl !== "#") {
      window.open(job.applyUrl, "_blank", "noopener,noreferrer");
    }
    onClose();
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal modal-sm" onClick={(e) => e.stopPropagation()}>
        <div className="modal-body" style={{textAlign:"center", padding: "40px 32px"}}>
          <div style={{
            width: 64, height: 64, borderRadius: "50%",
            background: "linear-gradient(180deg, var(--gold-500), var(--gold-700))",
            display: "grid", placeItems: "center", margin: "0 auto 20px",
            color: "var(--navy-900)",
            boxShadow: "0 8px 16px rgba(0,0,0,0.1)"
          }}>
            <Icon name="briefcase" size={32} stroke={2}/>
          </div>
          <h3 className="serif" style={{fontSize: 24, margin: "0 0 10px"}}>Ready to apply?</h3>
          <p style={{color:"var(--ink-3)", lineHeight: 1.6, margin:"0 0 24px"}}>
            You are about to be redirected to the official application portal for <b>{job.company}</b>. 
            Confirming this role is currently open and verified.
          </p>
          <div style={{display: "flex", gap: 12}}>
            <button className="btn btn-ghost" style={{flex: 1}} onClick={onClose}>Cancel</button>
            <button className="btn btn-primary" style={{flex: 2}} onClick={handleApply}>
              Go to portal <Icon name="arrowRight" size={14}/>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};


// ============== Message Modal ==============
const MessageModal = ({ title, body, icon = "bell", type = "info", onAction, onClose }) => {
  const colors = {
    success: "linear-gradient(180deg, var(--gold-500), var(--gold-700))",
    warning: "linear-gradient(180deg, #f59e0b, #d97706)",
    info: "linear-gradient(180deg, var(--navy-700), var(--navy-900))"
  };

  return (
    <div className="modal-backdrop" style={{zIndex: 1001}} onClick={onClose}>
      <div className="modal modal-sm" onClick={(e) => e.stopPropagation()}>
        <div className="modal-body" style={{textAlign:"center", padding: "40px 32px"}}>
          <div style={{
            width: 64, height: 64, borderRadius: "50%",
            background: colors[type] || colors.info,
            display: "grid", placeItems: "center", margin: "0 auto 20px",
            color: type === "success" ? "var(--navy-900)" : "#fff",
            boxShadow: "0 8px 16px rgba(0,0,0,0.1)"
          }}>
            <Icon name={icon} size={32} stroke={2}/>
          </div>
          <h3 className="serif" style={{fontSize: 24, margin: "0 0 10px"}}>{title}</h3>
          <p style={{color:"var(--ink-3)", lineHeight: 1.6, margin:"0 0 24px"}}>{body}</p>
          <button className="btn btn-primary btn-lg" style={{width: "100%"}} onClick={() => {
            if (onAction) onAction();
            else onClose();
          }}>
            {type === "warning" && title.includes("registered") ? "Go to Sign in" : 
             title.includes("Verify") ? "Proceed to Sign in" :
             type === "warning" ? "Resend Link" : "Got it"}
          </button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { JobDetailModal, AuthModal, ApplyModal, MessageModal });

