// screens.jsx — Home, Jobs, Saved, Admin, Insights, Countries
// Plus modals: JobDetail, AuthModal, AdminEditModal

// Helper to shuffle array
const shuffle = (arr) => {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
};

// =============== HOME ===============
const HomeScreen = ({ jobs, setRoute, onOpen, onSave, savedIds, density, setSearchSeed }) => {
  const featured = React.useMemo(() => {
    const verified = jobs.filter(j => j.visa.verified && j.status !== "closed" && j.active !== false);
    return shuffle(verified).slice(0, 6);
  }, [jobs]);
  const countries = window.COUNTRIES;

  const totalOpen = jobs.filter(j => j.active && j.status !== "closed").length;
  const verifiedThisWeek = jobs.filter(j => window.freshnessFromDate(j.verifiedDate) === "fresh").length;
  const prCount = jobs.filter(j => j.pr).length;
  const sponsors = new Set(jobs.map(j => j.company)).size;

  return (
    <>
      <section className="hero">
        <div className="container">
          <div className="hero-grid">
            <div>
              <div className="eyebrow delay-1"><span className="bar"></span> Global Mobility Intelligence · Est. 2024</div>
              <h1 className="delay-1">
                Move abroad on a job that <em>actually</em> sponsors your visa.
              </h1>
              <p className="lede delay-2">
                GYD verifies every sponsor licence, tracks every visa pathway, and timestamps every listing. No agent commissions, no consultancy nonsense — just open roles you can apply to today.
              </p>


              <div className="hero-search delay-3">
                <div className="field">
                  <Icon name="search" size={16} />
                  <input placeholder="Search roles, companies, skills…" onKeyDown={(e) => {
                    if (e.key === "Enter") { setSearchSeed({ q: e.target.value }); setRoute("jobs"); }
                  }}/>
                </div>
                <div className="field">
                  <Icon name="globe" size={16} />
                  <select defaultValue="" onChange={(e) => { if (e.target.value) { setSearchSeed({ country: e.target.value }); setRoute("jobs"); } }}>
                    <option value="">Anywhere</option>
                    {countries.map(c => <option key={c.code} value={c.code}>{c.flag} {c.name}</option>)}
                  </select>
                </div>
                <div className="field">
                  <Icon name="briefcase" size={16}/>
                  <select defaultValue="" onChange={(e) => { if (e.target.value) { setSearchSeed({ industry: e.target.value }); setRoute("jobs"); } }}>
                    <option value="">All industries</option>
                    {window.INDUSTRIES.map(i => <option key={i} value={i}>{i}</option>)}
                  </select>
                </div>
                <button className="btn btn-dark" onClick={() => setRoute("jobs")} style={{borderRadius: 6}}>Search jobs</button>
              </div>
            </div>

            <div>
              <div className="kpi-card delay-3">
                <div className="kpi-header" style={{textAlign: "center", marginBottom: 24}}>
                  <div style={{fontSize: 11, color: "var(--gold-500)", letterSpacing: "0.2em", marginBottom: 6, textTransform: "uppercase"}}>The GYD Index</div>
                  <div style={{fontFamily: "var(--f-display)", fontSize: 28, color: "var(--navy-900)", lineHeight: 1.1}}>Live market snapshot</div>
                </div>
                <div className="kpi-metrics">
                  <div className="kpi-row">
                    <span className="k">Verified sponsored roles</span>
                    <span className="v tabular"><CountUp end={totalOpen} /></span>
                  </div>
                  <div className="kpi-row">
                    <span className="k">Verified this week</span>
                    <span className="v tabular"><CountUp end={verifiedThisWeek} /></span>
                  </div>
                  <div className="kpi-row">
                    <span className="k">With PR pathway</span>
                    <span className="v tabular"><CountUp end={Math.round(prCount/jobs.length*100)} />%</span>
                  </div>

                </div>
              </div>
            </div>
          </div>
        </div>

        {/* ticker */}
        <div className="ticker">
          <div className="ticker-label">Verified today</div>
          <div className="ticker-track">
            {(() => {
              const tickerJobs = shuffle(jobs.filter(j => j.visa.verified)).slice(0, 10);
              return [...Array(2)].map((_, dup) => (
                <React.Fragment key={dup}>
                  {tickerJobs.map(j => (
                    <span key={`${dup}-${j.id}`} className="ti">
                      <b>{j.company}</b> · {j.title} · {j.city}, {j.country} 
                      <em>{j.visa.type} · {window.fmtSalary(j.salaryMin, j.salaryMax, j.currency)}</em>
                    </span>
                  ))}
                </React.Fragment>
              ));
            })()}
          </div>
        </div>
      </section>

      {/* Trust strip */}
      <div className="trust-strip">
        <div className="container">
          <span className="label">Sponsors we verify</span>
          <div className="marks">
            <span className="mk">SIEMENS</span>
            <span className="mk">Rolls-Royce</span>
            <span className="mk">ASML</span>
            <span className="mk">Bayer</span>
            <span className="mk">Stripe</span>
            <span className="mk">Lendlease</span>
            <span className="mk">DBS</span>
            <span className="mk">Lloyds</span>
          </div>
        </div>
      </div>

      <main className="container">
        <div className="section-head">
          <div className="left">
            <span className="eyebrow"><span className="bar"></span> Featured this week</span>
            <h2>Verified roles, ready to apply</h2>
            <span className="sub">Every employer below holds an active sponsor licence and has been independently confirmed by our verification team in the last 14 days.</span>
          </div>
          <div className="actions">
            <button className="btn btn-ghost" onClick={() => setRoute("jobs")}>View all {totalOpen} roles <Icon name="arrowRight" size={13}/></button>
          </div>
        </div>

        <div>
          {featured.map(j => (
            <JobRow key={j.id} job={j} density={density} onOpen={onOpen} onSave={onSave} isSaved={savedIds.has(j.id)} />
          ))}
        </div>

        <div className="section-head">
          <div className="left">
            <span className="eyebrow"><span className="bar"></span> By destination</span>
            <h2>Where India works abroad</h2>
            <span className="sub">Open roles, salary benchmarks, and PR pathways for the 12 most active sponsorship markets.</span>
          </div>
        </div>

        <div className="country-grid">
          {countries.map(c => {
            const cJobs = jobs.filter(j => j.country === c.code);
            const prShare = cJobs.length ? Math.round(cJobs.filter(j => j.pr).length / cJobs.length * 100) : 0;
            return (
              <button key={c.code} className="country-card" onClick={() => { setSearchSeed({ country: c.code }); setRoute("jobs"); }}>
                <div className="cname"><span style={{fontSize:22}}>{c.flag}</span><b>{c.name}</b></div>
                <div className="ctags">
                  {prShare >= 80 && <span className="badge badge-gold">PR pathway</span>}
                  {cJobs.some(j => !j.ielts) && <span className="badge badge-outline">No IELTS roles</span>}
                </div>
                <div className="cmeta">
                  <div>
                    <div className="cnum tabular">{c.openJobs.toLocaleString()}</div>
                    <div className="clbl">open roles</div>
                  </div>
                  <div style={{textAlign:"right"}}>
                    <div className="cnum tabular">{prShare}%</div>
                    <div className="clbl">PR-eligible</div>
                  </div>
                </div>
              </button>
            );
          })}
        </div>

        {/* How verification works */}
        <div className="section-head">
          <div className="left">
            <span className="eyebrow"><span className="bar"></span> The verification protocol</span>
            <h2>How a listing earns a "Verified Sponsor" badge</h2>
          </div>
        </div>
        <div className="verify-grid">
          {[
            { n: "01", t: "Sponsor licence check",       d: "We pull the employer's active sponsor record from the destination government register (e.g., UK Home Office, German BAMF, IRCC). Listing rejected if not on file." },
            { n: "02", t: "Recruiter confirmation",       d: "We speak directly with the hiring manager or in-house recruiter — no third-party agents. They confirm role, salary band, and visa type on the record." },
            { n: "03", t: "Document review",              d: "Job description, salary slab, and visa pathway are cross-checked against the destination country's minimum salary thresholds and shortage occupation lists." },
            { n: "04", t: "Continuous re-verification",   d: "Every 14 days we re-confirm the role is still open. If verification lapses, the Freshness badge shifts from Fresh → Active → Aging." },
          ].map((s, i) => (
            <div key={s.n} className="verify-card" style={{"--i": i}}>
              <div className="verify-num">{s.n}</div>
              <div className="verify-title">{s.t}</div>
              <div className="verify-desc">{s.d}</div>
              <div className="verify-bar"><div className="verify-bar-fill" style={{"--delay": `${i * 0.18}s`}}></div></div>
            </div>
          ))}
        </div>
      </main>
    </>
  );
};

// =============== JOBS / SEARCH ===============
const JobsScreen = ({ jobs, onOpen, onSave, savedIds, density, searchSeed }) => {
  const [query, setQuery] = React.useState(searchSeed?.q || "");
  const [country, setCountry] = React.useState(searchSeed?.country || "");
  const [industry, setIndustry] = React.useState(searchSeed?.industry || "");
  const [collar, setCollar] = React.useState([]);          // ['white','blue']
  const [sponsorship, setSponsorship] = React.useState([]);
  const [experience, setExperience] = React.useState([]);
  const [freshness, setFreshness] = React.useState([]);
  const [ieltsFilter, setIeltsFilter] = React.useState("any");
  const [prOnly, setPrOnly] = React.useState(false);
  const [verifiedOnly, setVerifiedOnly] = React.useState(false);
  const [sort, setSort] = React.useState("freshness");

  React.useEffect(() => {
    if (searchSeed) {
      if (searchSeed.q !== undefined) setQuery(searchSeed.q);
      if (searchSeed.country !== undefined) setCountry(searchSeed.country);
      if (searchSeed.industry !== undefined) setIndustry(searchSeed.industry);
    }
  }, [searchSeed]);

  const toggleArr = (arr, setArr, v) =>
    setArr(arr.includes(v) ? arr.filter(x => x !== v) : [...arr, v]);

  const filtered = React.useMemo(() => {
    let list = jobs.filter(j => j.active && j.status !== "closed");
    if (query.trim()) {
      const q = query.toLowerCase();
      list = list.filter(j =>
        j.title.toLowerCase().includes(q) ||
        j.company.toLowerCase().includes(q) ||
        j.industry.toLowerCase().includes(q) ||
        j.city.toLowerCase().includes(q)
      );
    }
    if (country) {
      list = list.filter(j => {
        if (!j.country) return false;
        const c = country.toUpperCase();
        const jc = j.country.toUpperCase();
        return jc === c || jc.includes(c) || c.includes(jc);
      });
    }
    if (industry) list = list.filter(j => j.industry === industry);
    if (collar.length) list = list.filter(j => collar.includes(j.collar));
    if (sponsorship.length) list = list.filter(j => sponsorship.includes(j.visa.sponsorshipType));
    if (experience.length) list = list.filter(j => experience.includes(j.experience));
    if (freshness.length) list = list.filter(j => freshness.includes(window.freshnessFromDate(j.verifiedDate)));
    if (ieltsFilter === "no") list = list.filter(j => !j.ielts);
    if (ieltsFilter === "yes") list = list.filter(j => j.ielts);
    if (prOnly) list = list.filter(j => j.pr);
    if (verifiedOnly) list = list.filter(j => j.visa.verified);

    list.sort((a, b) => {
      if (sort === "freshness") return new Date(b.verifiedDate) - new Date(a.verifiedDate);
      if (sort === "salary-hi") return b.salaryMax - a.salaryMax;
      if (sort === "salary-lo") return a.salaryMin - b.salaryMin;
      if (sort === "posted")    return new Date(b.posted) - new Date(a.posted);
      return 0;
    });

    return list;
  }, [jobs, query, country, industry, collar, sponsorship, experience, freshness, ieltsFilter, prOnly, verifiedOnly, sort]);

  const countByCountry = (code) => jobs.filter(j => {
    if (!j.active || j.status === "closed") return false;
    if (!j.country) return false;
    const c = code.toUpperCase();
    const jc = j.country.toUpperCase();
    return jc === c || jc.includes(c) || c.includes(jc);
  }).length;
  const countByCollar  = (c) => jobs.filter(j => j.collar === c && j.active).length;
  const countBySponsorship = (s) => jobs.filter(j => j.visa.sponsorshipType === s && j.active).length;
  const countByExp = (e) => jobs.filter(j => j.experience === e && j.active).length;
  const countByFresh = (f) => jobs.filter(j => window.freshnessFromDate(j.verifiedDate) === f && j.active).length;

  return (
    <div className="container">
      <div className="layout-search">
        {/* Filters */}
        <aside className="filters">
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8}}>
            <h4 style={{margin:0}}>Filters</h4>
            <button className="btn-link" style={{fontSize:12}} onClick={() => {
              setQuery(""); setCountry(""); setIndustry(""); setCollar([]); setSponsorship([]);
              setExperience([]); setFreshness([]); setIeltsFilter("any"); setPrOnly(false); setVerifiedOnly(false);
            }}>Clear all</button>
          </div>

          <div className="filter-group">
            <h4>Country</h4>
            {window.COUNTRIES.slice(0, 8).map(c => (
              <label key={c.code} className="filter-opt">
                <input type="radio" name="country" checked={country === c.code} onChange={() => setCountry(country === c.code ? "" : c.code)} />
                <span style={{display:"inline-flex", gap:8, alignItems:"center"}}><span>{c.flag}</span> {c.name}</span>
                <span className="count">{countByCountry(c.code)}</span>
              </label>
            ))}
            <button className="btn-link" style={{fontSize:12, marginTop:6}}>Show all 12 countries</button>
          </div>

          <div className="filter-group">
            <h4>Industry</h4>
            <select className="select" value={industry} onChange={(e) => setIndustry(e.target.value)} style={{height: 34}}>
              <option value="">All industries</option>
              {window.INDUSTRIES.map(i => <option key={i} value={i}>{i}</option>)}
            </select>
          </div>

          <div className="filter-group">
            <h4>Collar</h4>
            {["white", "blue"].map(c => (
              <label key={c} className="filter-opt">
                <input type="checkbox" checked={collar.includes(c)} onChange={() => toggleArr(collar, setCollar, c)} />
                <span style={{textTransform:"capitalize"}}>{c} collar</span>
                <span className="count">{countByCollar(c)}</span>
              </label>
            ))}
          </div>

          <div className="filter-group">
            <h4>Sponsorship type</h4>
            {window.SPONSORSHIP_TYPES.map(s => (
              <label key={s} className="filter-opt">
                <input type="checkbox" checked={sponsorship.includes(s)} onChange={() => toggleArr(sponsorship, setSponsorship, s)} />
                <span>{s}</span>
                <span className="count">{countBySponsorship(s)}</span>
              </label>
            ))}
          </div>

          <div className="filter-group">
            <h4>Experience</h4>
            {window.EXPERIENCE_LEVELS.map(e => (
              <label key={e} className="filter-opt">
                <input type="checkbox" checked={experience.includes(e)} onChange={() => toggleArr(experience, setExperience, e)} />
                <span>{e}</span>
                <span className="count">{countByExp(e)}</span>
              </label>
            ))}
          </div>

          <div className="filter-group">
            <h4>Freshness</h4>
            {["fresh", "active", "aging"].map(f => (
              <label key={f} className="filter-opt">
                <input type="checkbox" checked={freshness.includes(f)} onChange={() => toggleArr(freshness, setFreshness, f)} />
                <span style={{textTransform:"capitalize"}}>{f}</span>
                <span className="count">{countByFresh(f)}</span>
              </label>
            ))}
          </div>

          <div className="filter-group">
            <h4>IELTS</h4>
            {[
              {v: "any", l: "Any"},
              {v: "no", l: "Not required"},
              {v: "yes", l: "Required"},
            ].map(o => (
              <label key={o.v} className="filter-opt">
                <input type="radio" name="ielts" checked={ieltsFilter === o.v} onChange={() => setIeltsFilter(o.v)} />
                <span>{o.l}</span>
              </label>
            ))}
          </div>

          <div className="filter-group">
            <label className="filter-opt">
              <input type="checkbox" checked={prOnly} onChange={(e) => setPrOnly(e.target.checked)} />
              <span>PR pathway only</span>
            </label>
            <label className="filter-opt">
              <input type="checkbox" checked={verifiedOnly} onChange={(e) => setVerifiedOnly(e.target.checked)} />
              <span>Verified sponsors only</span>
            </label>
          </div>
        </aside>

        {/* Results */}
        <div>
          <div className="search-bar">
            <div className="field">
              <Icon name="search" size={15}/>
              <input placeholder="Search roles, companies, skills…" value={query} onChange={(e) => setQuery(e.target.value)} />
            </div>
            <div className="field" style={{flex: 0.5}}>
              <Icon name="globe" size={15}/>
              <select value={country} onChange={(e) => setCountry(e.target.value)}>
                <option value="">Anywhere</option>
                {window.COUNTRIES.map(c => <option key={c.code} value={c.code}>{c.flag} {c.name}</option>)}
              </select>
            </div>
            <button className="btn btn-dark btn-sm">Search</button>
          </div>

          <div className="result-meta">
            <span><b>{filtered.length}</b> verified sponsored roles match</span>
            <div style={{display:"flex",alignItems:"center",gap:8}}>
              <span>Sort by</span>
              <select value={sort} onChange={(e) => setSort(e.target.value)} style={{height: 32, border: 0, background: "transparent", color: "var(--navy-800)", fontWeight: 600, cursor:"pointer"}}>
                <option value="freshness">Most recently verified</option>
                <option value="posted">Newest posting</option>
                <option value="salary-hi">Highest salary</option>
                <option value="salary-lo">Lowest salary</option>
              </select>
            </div>
          </div>

          {filtered.length === 0 ? (
            <div className="card" style={{padding: 40, textAlign:"center"}}>
              <div style={{fontFamily:"var(--f-display)", fontSize: 24, marginBottom: 6}}>No matches</div>
              <div style={{color:"var(--ink-3)", marginBottom: 16}}>Try removing a filter or two — your criteria may be too narrow.</div>
            </div>
          ) : filtered.map(j => (
            <JobRow key={j.id} job={j} density={density} onOpen={onOpen} onSave={onSave} isSaved={savedIds.has(j.id)} />
          ))}
        </div>
      </div>
    </div>
  );
};

// =============== SAVED ===============
const SavedScreen = ({ jobs, savedIds, onOpen, onSave, density, user, onSignIn }) => {
  if (!user) {
    return (
      <div className="container" style={{padding: "80px 0"}}>
        <div className="card" style={{maxWidth: 520, margin: "0 auto", padding: 40, textAlign:"center"}}>
          <Icon name="bookmark" size={36} stroke={1.4} />
          <h3 className="serif" style={{fontSize: 28, margin: "12px 0 6px"}}>Save jobs to your shortlist</h3>
          <p style={{color:"var(--ink-3)"}}>Create an account or sign in to bookmark roles, get verification alerts, and track your applications.</p>
          <button className="btn btn-primary btn-lg" style={{marginTop: 16}} onClick={onSignIn}>Sign in to continue</button>
        </div>
      </div>
    );
  }
  const saved = jobs.filter(j => savedIds.has(j.id));
  return (
    <div className="container" style={{padding: "32px 0 64px"}}>
      <div className="section-head" style={{margin:"0 0 24px"}}>
        <div className="left">
          <span className="eyebrow"><span className="bar"></span> Your shortlist</span>
          <h2>Saved jobs</h2>
          <span className="sub">{saved.length} roles saved · we'll email you if verification status changes.</span>
        </div>
      </div>
      {saved.length === 0 ? (
        <div className="card" style={{padding: 40, textAlign:"center", color:"var(--ink-3)"}}>
          Nothing saved yet — tap the bookmark icon on any job to add it here.
        </div>
      ) : saved.map(j => (
        <JobRow key={j.id} job={j} density={density} onOpen={onOpen} onSave={onSave} isSaved={true} />
      ))}
    </div>
  );
};



// ---------- Countries Screen ----------
const CountriesScreen = ({ jobs, setSearchSeed, setRoute }) => {
  const countries = window.COUNTRIES || [];
  
  return (
    <div className="container" style={{ padding: "40px 0" }}>
      <div className="section-head" style={{ marginTop: 0 }}>
        <div className="left">
          <h2 className="serif">Explore by Country</h2>
          <div className="sub">Find verified sponsored roles in top global markets.</div>
        </div>
      </div>
      
      <div className="country-grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: "24px" }}>
        {countries.map(c => {
          const count = jobs.filter(j => j.country === c.code).length;
          return (
            <div key={c.code} className="country-card" onClick={() => {
              setSearchSeed({ country: c.code });
              setRoute("jobs");
            }} style={{ padding: "24px" }}>
              <div className="cname" style={{ marginBottom: "16px" }}>
                <span style={{ fontSize: "32px" }}>{c.flag}</span> 
                <b style={{ fontSize: "24px", marginLeft: "12px" }}>{c.name}</b>
              </div>
              <div className="cmeta" style={{ borderTop: "1px solid var(--line-2)", paddingTop: "16px", marginTop: "auto" }}>
                <div className="clbl" style={{ fontSize: "12px", color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.05em" }}>Verified Sponsored Roles</div>
                <div className="cnum" style={{ fontSize: "32px", fontFamily: "var(--f-display)", color: "var(--navy-900)" }}>{count || c.openJobs}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// =============== ADMIN PANEL ===============
const AdminScreen = ({ jobs, setJobs, setRoute }) => {
  const [activeTab, setActiveTab] = React.useState("jobs"); // "jobs" or "users"
  const [users, setUsers] = React.useState([]);
  const [loadingUsers, setLoadingUsers] = React.useState(false);
  const [form, setForm] = React.useState({
    title: "",
    company: "",
    country: "GB",
    city: "",
    industry: "Tech",
    collar: "white",
    experience: "Mid-Senior",
    salaryMin: "",
    salaryMax: "",
    currency: "GBP",
    visaType: "Skilled Worker Visa",
    applyUrl: "",
    description: "",
    benefits: "Visa sponsorship provided"
  });
  const [submitting, setSubmitting] = React.useState(false);
  const [message, setMessage] = React.useState("");

  // Load registered users from Firestore
  React.useEffect(() => {
    if (activeTab === "users") {
      setLoadingUsers(true);
      if (window.db) {
        window.db.collection("users").get()
          .then(snapshot => {
            const list = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
            // Sort by createdAt or lastLogin
            list.sort((a, b) => {
              const dateA = a.createdAt?.toDate?.() || new Date(a.createdAt || 0);
              const dateB = b.createdAt?.toDate?.() || new Date(b.createdAt || 0);
              return dateB - dateA;
            });
            setUsers(list);
            setLoadingUsers(false);
          })
          .catch(err => {
            console.error("Failed to load users from Firestore:", err);
            // Fallback mock users for demonstration if offline
            setUsers([
              { id: "u-1", name: "Rohan Sharma", email: "rohan@gmail.com", createdAt: new Date(Date.now() - 48 * 3600000), lastLogin: new Date() },
              { id: "u-2", name: "Priya Patel", email: "priya.patel@outlook.com", createdAt: new Date(Date.now() - 120 * 3600000), lastLogin: new Date(Date.now() - 24 * 3600000) }
            ]);
            setLoadingUsers(false);
          });
      } else {
        setLoadingUsers(false);
      }
    }
  }, [activeTab]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setForm(prev => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.title || !form.company || !form.country || !form.applyUrl) {
      alert("Please fill in all required fields (Title, Company, Country, Apply URL).");
      return;
    }

    setSubmitting(true);
    setMessage("");

    const newJob = {
      title: form.title,
      company: form.company,
      country: form.country,
      city: form.city,
      industry: form.industry,
      collar: form.collar,
      experience: form.experience,
      salaryMin: Number(form.salaryMin) || 0,
      salaryMax: Number(form.salaryMax) || 0,
      currency: form.currency,
      visa: {
        sponsored: true,
        type: form.visaType,
        sponsorshipType: "Full sponsorship",
        verified: true
      },
      posted: new Date().toISOString().slice(0, 10),
      verifiedDate: new Date().toISOString().slice(0, 10),
      description: form.description || `${form.title} role at ${form.company} with verified visa sponsorship.`,
      benefits: [form.benefits || "Visa sponsorship provided"],
      applyUrl: form.applyUrl,
      status: "active",
      active: true
    };

    try {
      const response = await fetch("/api/jobs", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(newJob)
      });

      const res = await response.json();
      if (res.success) {
        // Prepend to local React state so it shows up instantly!
        setJobs(prev => [res.data, ...prev]);
        setMessage("🎉 Job created and published successfully!");
        
        // Reset form
        setForm({
          title: "",
          company: "",
          country: "GB",
          city: "",
          industry: "Tech",
          collar: "white",
          experience: "Mid-Senior",
          salaryMin: "",
          salaryMax: "",
          currency: "GBP",
          visaType: "Skilled Worker Visa",
          applyUrl: "",
          description: "",
          benefits: "Visa sponsorship provided"
        });
      } else {
        alert("Error: " + (res.error || "Failed to create job"));
      }
    } catch (err) {
      console.error("Failed to post job:", err);
      alert("Network error: Failed to post job.");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="container" style={{ padding: "40px 0 80px" }}>
      <div className="section-head" style={{ marginTop: 0, borderBottom: "1px solid var(--line-2)", paddingBottom: "20px", marginBottom: "32px" }}>
        <div className="left">
          <span className="eyebrow"><span className="bar"></span> Management Center</span>
          <h2 className="serif" style={{ fontSize: "36px", color: "var(--navy-900)" }}>GYD Admin Dashboard</h2>
          <div className="sub">Manage visa sponsorship listings and view registered candidates.</div>
        </div>
        <div className="right" style={{ display: "flex", gap: "12px", marginTop: "16px" }}>
          <button 
            className={`btn ${activeTab === "jobs" ? "btn-dark" : "btn-nav-ghost"}`} 
            onClick={() => setActiveTab("jobs")}
          >
            Add New Job
          </button>
          <button 
            className={`btn ${activeTab === "users" ? "btn-dark" : "btn-nav-ghost"}`} 
            onClick={() => setActiveTab("users")}
          >
            Registered Users
          </button>
        </div>
      </div>

      {activeTab === "jobs" ? (
        <div className="card" style={{ padding: "32px", maxWidth: "800px", margin: "0 auto" }}>
          <h3 className="serif" style={{ fontSize: "24px", marginBottom: "20px", borderBottom: "1px solid var(--line-2)", paddingBottom: "12px" }}>
            Add Visa Sponsored Job
          </h3>
          
          {message && (
            <div style={{ background: "rgba(16, 185, 129, 0.1)", border: "1px solid #10b981", color: "#047857", padding: "12px", borderRadius: "6px", marginBottom: "24px", fontWeight: 500 }}>
              {message}
            </div>
          )}

          <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px" }}>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Job Title *</label>
                <input 
                  type="text" 
                  name="title" 
                  value={form.title} 
                  onChange={handleChange} 
                  placeholder="e.g. Lead React Developer" 
                  required
                  style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
                />
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Company Name *</label>
                <input 
                  type="text" 
                  name="company" 
                  value={form.company} 
                  onChange={handleChange} 
                  placeholder="e.g. Google DeepMind" 
                  required
                  style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
                />
              </div>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px" }}>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Country *</label>
                <select 
                  name="country" 
                  value={form.country} 
                  onChange={handleChange}
                  style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
                >
                  {(window.COUNTRIES || []).map(c => (
                    <option key={c.code} value={c.code}>{c.flag} {c.name}</option>
                  ))}
                </select>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>City</label>
                <input 
                  type="text" 
                  name="city" 
                  value={form.city} 
                  onChange={handleChange} 
                  placeholder="e.g. London" 
                  style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
                />
              </div>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "16px" }}>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Industry</label>
                <select 
                  name="industry" 
                  value={form.industry} 
                  onChange={handleChange}
                  style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
                >
                  {(window.INDUSTRIES || []).map(ind => (
                    <option key={ind} value={ind}>{ind}</option>
                  ))}
                </select>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Collar</label>
                <select 
                  name="collar" 
                  value={form.collar} 
                  onChange={handleChange}
                  style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
                >
                  <option value="white">White Collar</option>
                  <option value="blue">Blue Collar</option>
                </select>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Experience Level</label>
                <input 
                  type="text" 
                  name="experience" 
                  value={form.experience} 
                  onChange={handleChange} 
                  placeholder="e.g. Senior (5+ yrs)" 
                  style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
                />
              </div>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "16px" }}>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Min Salary</label>
                <input 
                  type="number" 
                  name="salaryMin" 
                  value={form.salaryMin} 
                  onChange={handleChange} 
                  placeholder="Optional" 
                  style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
                />
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Max Salary</label>
                <input 
                  type="number" 
                  name="salaryMax" 
                  value={form.salaryMax} 
                  onChange={handleChange} 
                  placeholder="Optional" 
                  style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
                />
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Currency</label>
                <select 
                  name="currency" 
                  value={form.currency} 
                  onChange={handleChange}
                  style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
                >
                  <option value="GBP">GBP (£)</option>
                  <option value="EUR">EUR (€)</option>
                  <option value="USD">USD ($)</option>
                  <option value="AUD">AUD ($)</option>
                  <option value="CAD">CAD ($)</option>
                </select>
              </div>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px" }}>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Visa Type</label>
                <input 
                  type="text" 
                  name="visaType" 
                  value={form.visaType} 
                  onChange={handleChange} 
                  placeholder="e.g. Skilled Worker Visa" 
                  style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
                />
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Apply URL *</label>
                <input 
                  type="url" 
                  name="applyUrl" 
                  value={form.applyUrl} 
                  onChange={handleChange} 
                  placeholder="e.g. https://careers.company.com/role" 
                  required
                  style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
                />
              </div>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
              <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Job Description</label>
              <textarea 
                name="description" 
                value={form.description} 
                onChange={handleChange} 
                placeholder="Detailed description of responsibilities and visa sponsorship eligibility..."
                rows={4}
                style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", fontFamily: "sans-serif", background: "var(--bg)", color: "var(--navy-900)" }}
              />
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
              <label style={{ fontWeight: 600, fontSize: "13px", color: "var(--navy-900)" }}>Benefits & Perks</label>
              <input 
                type="text" 
                name="benefits" 
                value={form.benefits} 
                onChange={handleChange} 
                placeholder="e.g. Full visa sponsorship + relocation allowance" 
                style={{ padding: "10px", borderRadius: "6px", border: "1px solid var(--line-3)", background: "var(--bg)", color: "var(--navy-900)" }}
              />
            </div>

            <button 
              type="submit" 
              className="btn btn-dark" 
              disabled={submitting}
              style={{ padding: "14px", borderRadius: "6px", fontWeight: 600, fontSize: "15px", marginTop: "12px", width: "100%" }}
            >
              {submitting ? "Publishing Job..." : "Publish Job Live"}
            </button>
          </form>
        </div>
      ) : (
        <div className="card" style={{ padding: "32px" }}>
          <h3 className="serif" style={{ fontSize: "24px", marginBottom: "20px", borderBottom: "1px solid var(--line-2)", paddingBottom: "12px" }}>
            Registered Users ({users.length})
          </h3>
          
          {loadingUsers ? (
            <div style={{ textAlign: "center", padding: "40px", color: "var(--ink-3)" }}>Loading registered users from Firestore...</div>
          ) : users.length === 0 ? (
            <div style={{ textAlign: "center", padding: "40px", color: "var(--ink-3)" }}>No registered users found.</div>
          ) : (
            <div style={{ overflowX: "auto" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", textAlign: "left" }}>
                <thead>
                  <tr style={{ borderBottom: "2px solid var(--line-2)", color: "var(--navy-900)", fontWeight: 600, fontSize: "13px" }}>
                    <th style={{ padding: "12px 8px" }}>Name</th>
                    <th style={{ padding: "12px 8px" }}>Email</th>
                    <th style={{ padding: "12px 8px" }}>Registered At</th>
                    <th style={{ padding: "12px 8px" }}>Last Active</th>
                    <th style={{ padding: "12px 8px" }}>Saved Roles</th>
                  </tr>
                </thead>
                <tbody>
                  {users.map(u => {
                    const createdDate = u.createdAt?.toDate?.() || new Date(u.createdAt) || new Date();
                    const loginDate = u.lastLogin?.toDate?.() || new Date(u.lastLogin) || new Date();
                    return (
                      <tr key={u.id} style={{ borderBottom: "1px solid var(--line-3)", fontSize: "14px", color: "var(--navy-800)" }}>
                        <td style={{ padding: "16px 8px", fontWeight: 600 }}>{u.name}</td>
                        <td style={{ padding: "16px 8px" }}>{u.email}</td>
                        <td style={{ padding: "16px 8px" }}>{createdDate.toLocaleDateString()}</td>
                        <td style={{ padding: "16px 8px" }}>{loginDate.toLocaleDateString()} {loginDate.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</td>
                        <td style={{ padding: "16px 8px" }}>
                          <span style={{ background: "var(--gold-500)", color: "var(--navy-900)", padding: "4px 8px", borderRadius: "12px", fontSize: "11px", fontWeight: 600 }}>
                            {(u.savedIds || []).length} saved
                          </span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { HomeScreen, JobsScreen, SavedScreen, CountriesScreen, AdminScreen });
