/* Takotasks — Active Projects page: filter chips + role list + role detail modal */

function ActiveProjectsPage() {
  const [active, setActive] = React.useState("All roles");
  const [country, setCountry] = React.useState("Anywhere");
  const [openRole, setOpenRole] = React.useState(null);

  // Open from URL hash on load (e.g. /active-projects.html#r3)
  React.useEffect(() => {
    const id = window.location.hash.replace("#", "");
    if (!id) return;
    const role = ROLES.find((r) => r.id === id);
    if (role) setOpenRole(role);
  }, []);

  // Lock body scroll when modal is open
  React.useEffect(() => {
    document.body.style.overflow = openRole ? "hidden" : "";
    return () => {document.body.style.overflow = "";};
  }, [openRole]);

  const countries = ["Anywhere", "Philippines", "Kenya", "Ecuador"];

  const filtered = ROLES.filter((r) => {
    if (active !== "All roles" && r.category !== active) return false;
    if (country !== "Anywhere" && r.location !== country) return false;
    return true;
  });

  return (
    <PageFade>
      <CursorHalo />
      <TopNav current="active-projects" />
      <ProjectsHero count={ROLES.length} />

      <section className="tt-band tt-band--soft" style={{ paddingTop: 0 }}>
        <div className="tt-container">
          <Reveal>
            <div className="tt-filters">
              {CATEGORIES.map((c) =>
              <button
                key={c}
                className={cx("tt-filter", active === c && "tt-filter--active")}
                onClick={() => setActive(c)}>
                
                  {c}
                </button>
              )}
            </div>
          </Reveal>

          <Reveal delay={60}>
            <div className="tt-filters" style={{ marginBottom: 8 }}>
              <span style={{ alignSelf: "center", fontSize: 13, color: "var(--tt-muted)", marginRight: 8, letterSpacing: 1.2, textTransform: "uppercase", fontWeight: 600 }}>
                Country ·
              </span>
              {countries.map((c) =>
              <button
                key={c}
                className={cx("tt-filter", country === c && "tt-filter--active")}
                onClick={() => setCountry(c)}>
                
                  {c}
                </button>
              )}
            </div>
          </Reveal>

          <Reveal delay={120}>
            <div style={{
              display: "flex", justifyContent: "space-between",
              alignItems: "baseline", margin: "24px 0 12px"
            }}>
              <span style={{ color: "var(--tt-muted)", fontSize: 14 }}>
                Showing <strong style={{ color: "var(--tt-ink)" }}>{filtered.length}</strong> {filtered.length === 1 ? "role" : "roles"}
                {active !== "All roles" && <> in <strong style={{ color: "var(--tt-ink)" }}>{active}</strong></>}
                {country !== "Anywhere" && <> · <strong style={{ color: "var(--tt-ink)" }}>{country}</strong></>}
              </span>
              <a className="tt-arrow-link" href="contact.html" style={{ fontSize: 14 }}>Don't see your role? Join our database

              </a>
            </div>
          </Reveal>

          {filtered.length === 0 ?
          <EmptyState onReset={() => {setActive("All roles");setCountry("Anywhere");}} /> :

          <div className="tt-roles-list">
              {filtered.map((r, i) =>
            <Reveal key={r.id} delay={i * 40} y={16}>
                  <a
                href={`#${r.id}`}
                className="tt-role-row"
                onClick={(e) => {
                  e.preventDefault();
                  setOpenRole(r);
                  window.history.replaceState(null, "", `#${r.id}`);
                }}>
                
                    <span className="tt-role-row__num">{String(i + 1).padStart(2, "0")}</span>
                    <div>
                      <div className="tt-role-row__role">{r.role}</div>
                      <div className="tt-role-row__status" style={{ marginTop: 8, display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
                        {r.status === "open" && <Badge variant="status" dot="#7FC970">Open</Badge>}
                        {r.status === "filling" && <Badge variant="status" dot="#DA4331">Filling soon</Badge>}
                        <span style={{ fontSize: 13, color: "var(--tt-muted)" }}>· {r.type}</span>
                      </div>
                    </div>
                    <div className="tt-role-row__desc">{r.team}</div>
                    <div className="tt-role-row__meta">
                      <span><Icon name="map-pin" size={13} style={{ verticalAlign: "-2px" }} /> {r.location}</span>
                      <span>{r.region}</span>
                      <span>{r.pay}</span>
                    </div>
                    <span className="tt-role-row__arrow" aria-hidden="true">
                      <Icon name="arrow-right" size={16} />
                    </span>
                  </a>
                </Reveal>
            )}
            </div>
          }
        </div>
      </section>

      <CategoriesBand />

      {openRole &&
      <RoleModal role={openRole} onClose={() => {
        setOpenRole(null);
        window.history.replaceState(null, "", window.location.pathname);
      }} />
      }

      <Footer />
    </PageFade>);

}

function ProjectsHero({ count }) {
  return (
    <section className="tt-hero tt-hero--light" style={{ paddingTop: 120, paddingBottom: 56 }}>
      <div className="tt-container">
        <div className="tt-hero__solo" style={{ maxWidth: 1100 }}>
          <Reveal><Eyebrow>Active projects · {count} live</Eyebrow></Reveal>
          <Reveal delay={80}>
            <h1 className="tt-hero-display" style={{ fontSize: "clamp(44px, 7vw, 96px)" }}>
              Open roles<br />
              we're hiring for<br />
              <em>right now.</em>
            </h1>
          </Reveal>
          <Reveal delay={160}>
            <p className="tt-lead" style={{ maxWidth: "56ch", fontSize: 19 }}>
              Honest descriptions, real teams (kept anonymous for confidentiality),
              and the commitment up front. We update this list weekly.
            </p>
          </Reveal>
        </div>
      </div>
    </section>);

}

function CategoriesBand() {
  const tiles = [
  { title: "Customer Support", body: "Email, chat and lightweight phone work for product teams.", cls: "tt-tile--grad" },
  { title: "Data Labeling", body: "Image, text, audio. Always with a real QA loop.", cls: "tt-tile--soft" },
  { title: "Content Moderation", body: "Trust & Safety reviews with rotating queues.", cls: "tt-tile--sky" },
  { title: "Creative", body: "Video editors, brand designers, motion.", cls: "tt-tile--dark" },
  { title: "Operations", body: "EAs, ops coordinators, community managers.", cls: "tt-tile--secondary" },
  { title: "Human-in-the-loop", body: "Model output rating, short-form correction.", cls: "tt-tile--grad" }];

  return (
    <section className="tt-band">
      <div className="tt-container">
        <div className="tt-section-head" style={{ display: "flex", justifyContent: "space-between", maxWidth: "none", alignItems: "flex-end", marginBottom: 32 }}>
          <div style={{ maxWidth: 520 }}>
            <Reveal><Eyebrow>The kinds of work we place</Eyebrow></Reveal>
            <Reveal delay={80}><h2 style={{ marginTop: 12 }}>Six categories. Real teams behind each.</h2></Reveal>
          </div>
          <Reveal delay={140}>
            <a href="contact.html" className="tt-arrow-link">
              Apply for any
              <span className="tt-arrow-link__bullet"><Icon name="arrow-right" size={16} /></span>
            </a>
          </Reveal>
        </div>

        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(3, 1fr)",
          gap: "var(--tt-space-md)"
        }} className="tt-cats-grid">
          {tiles.map((t, i) =>
          <Reveal key={t.title} delay={i * 60}>
              <div className={cx("tt-tile", t.cls)}>
                <div className="tt-tile__content">
                  <h4>{t.title}</h4>
                  <p>{t.body}</p>
                </div>
              </div>
            </Reveal>
          )}
        </div>
        <style>{`
          @media (max-width: 900px) {
            .tt-cats-grid { grid-template-columns: repeat(2, 1fr) !important; }
          }
          @media (max-width: 600px) {
            .tt-cats-grid { grid-template-columns: 1fr !important; }
          }
        `}</style>
      </div>
    </section>);

}

function EmptyState({ onReset }) {
  return (
    <div style={{
      background: "var(--tt-surface-card)",
      borderRadius: "var(--tt-radius-lg)",
      padding: 56, textAlign: "center", marginTop: 24
    }}>
      <h3 style={{
        fontFamily: "var(--tt-font-display)", fontWeight: 500,
        fontSize: 28, marginBottom: 12
      }}>
        No matches with those filters.
      </h3>
      <p style={{ marginInline: "auto", maxWidth: "44ch", marginBottom: 24 }}>
        Try widening the filters, or send us your details — we'll reach out
        when something fits.
      </p>
      <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
        <Button variant="primary" onClick={onReset}>Reset filters</Button>
        <Button variant="secondary" href="contact.html?lane=work">Send us your details anyway</Button>
      </div>
    </div>);

}

function RoleModal({ role, onClose }) {
  // Close on escape
  React.useEffect(() => {
    const k = (e) => {if (e.key === "Escape") onClose();};
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, [onClose]);

  return (
    <div className="tt-modal-backdrop" onClick={onClose}>
      <div className="tt-modal" onClick={(e) => e.stopPropagation()}>
        <div className="tt-modal__head">
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            {role.status === "open" && <Badge variant="status" dot="#7FC970">Open</Badge>}
            {role.status === "filling" && <Badge variant="status" dot="#DA4331">Filling soon</Badge>}
            <span style={{ fontSize: 13, color: "var(--tt-muted)" }}>{role.posted}</span>
          </div>
          <button className="tt-modal__close" onClick={onClose} aria-label="Close">
            <Icon name="x" size={18} />
          </button>
        </div>

        <div className="tt-modal__body">
          <Eyebrow>{role.category} · {role.location}</Eyebrow>
          <h2 className="tt-modal__role">{role.role}</h2>
          <p style={{ fontSize: 18, lineHeight: 1.6, color: "var(--tt-body)" }}>{role.desc}</p>

          <div className="tt-modal__meta-grid">
            <div><div>Type</div><div>{role.type}</div></div>
            <div><div>Hours</div><div>{role.hours}</div></div>
            <div><div>Pay</div><div>{role.pay}</div></div>
            <div><div>Timezone</div><div>{role.region}</div></div>
          </div>

          <div className="tt-modal__sec">
            <h4>What we're looking for</h4>
            <ul>
              {role.requirements.map((r) =>
              <li key={r}><Icon name="check" size={18} /><span>{r}</span></li>
              )}
            </ul>
          </div>

          <div className="tt-modal__sec">
            <h4>What you get</h4>
            <ul>
              {role.perks.map((p) =>
              <li key={p}><Icon name="check" size={18} /><span>{p}</span></li>
              )}
            </ul>
          </div>

          <div className="tt-modal__sec" style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap", marginTop: 32 }}>
            <Button
              variant="primary"
              href={role.applyUrl || `contact.html?lane=work&role=${encodeURIComponent(role.role)}`}
              {...(role.applyUrl ? { target: "_blank", rel: "noopener noreferrer" } : {})}
            >
              {role.applyUrl ? "Sign up for this role" : "Apply for this role"} <Icon name="arrow-right" size={18} />
            </Button>

          </div>

          <div style={{
            marginTop: 32, padding: 20,
            background: "var(--tt-surface-sky-soft)",
            borderRadius: "var(--tt-radius-md)",
            display: "flex", gap: 12, alignItems: "flex-start"
          }}>
            <Icon name="shield" size={20} style={{ color: "var(--tt-primary)", flexShrink: 0, marginTop: 2 }} />
            <div style={{ fontSize: 14, lineHeight: 1.6, color: "var(--tt-body)" }}>
              <strong style={{ color: "var(--tt-ink)" }}>No platform fees.</strong> Takotasks is paid by the
              client. We never deduct from your wage. The client name is
              shared after the first interview — we keep it anonymous here for
              confidentiality.
            </div>
          </div>
        </div>
      </div>
    </div>);

}

window.ActiveProjectsPage = ActiveProjectsPage;