// screens-home.jsx — Landing, Browse, How it works
const { useState: useS1, useEffect: useE1 } = React;

const Wrap = ({ children, style }) => (
  <div style={{ maxWidth: 1200, margin: "0 auto", padding: "0 24px", ...style }}>{children}</div>
);

function SectionLabel({ children }) {
  return <div style={{
    display: "inline-flex", alignItems: "center", gap: 8, fontSize: 13, fontWeight: 700,
    textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--clay)",
  }}><span style={{ width: 22, height: 2, background: "var(--clay)" }} />{children}</div>;
}

/* ============ LANDING ============ */
function Landing({ go, openTask, onPost, tasks }) {
  const rotators = ["a store check", "a sign held", "a gift delivered", "an event covered", "a couch carried", "a review posted"];
  const [ri, setRi] = useS1(0);
  useE1(() => { const t = setInterval(() => setRi((i) => (i + 1) % rotators.length), 2000); return () => clearInterval(t); }, []);
  const featured = (tasks || TASKS).filter((t) => !isTaskExpired(t)).slice(0, 6);

  return (
    <div>
      {/* hero */}
      <div style={{ position: "relative", overflow: "hidden" }}>
        <Wrap style={{ paddingTop: 72, paddingBottom: 60 }}>
          <div style={{ maxWidth: 760 }}>
            <SectionLabel>The real-world layer for getting things done</SectionLabel>
            <h1 style={{
              fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(38px, 5.6vw, 68px)",
              lineHeight: 1.05, letterSpacing: "-0.035em", color: "var(--ink)", margin: "20px 0 0", textWrap: "balance",
            }}>
              Need something done?<br />
              <span style={{ color: "var(--clay)" }}>Find your human.</span>
            </h1>
            <p style={{ fontSize: "clamp(17px, 2vw, 21px)", lineHeight: 1.5, color: "var(--ink-2)", maxWidth: 560, margin: "30px 0 0", fontWeight: 450 }}>
              Post a task — a real person nearby picks it up and gets it done. From <span style={{ color: "var(--ink)", fontWeight: 600, borderBottom: "2px solid var(--clay)" }}>{rotators[ri]}</span> to anything in between.
            </p>
            <div style={{ display: "flex", gap: 12, marginTop: 32, flexWrap: "wrap" }}>
              <Button size="lg" icon="plus" onClick={onPost}>Post a task</Button>
              <Button size="lg" variant="ghost" iconRight="arrow" onClick={() => go("browse")}>Browse tasks</Button>
            </div>
            <div style={{ display: "flex", gap: 30, marginTop: 40, flexWrap: "wrap" }}>
              {[["12,400+", "humans nearby"], ["4.9★", "avg. rating"], ["2 min", "to post a task"]].map(([n, l]) => (
                <div key={l}>
                  <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 26, letterSpacing: "-0.02em", color: "var(--ink)" }}>{n}</div>
                  <div style={{ fontSize: 13.5, color: "var(--ink-2)", fontWeight: 500 }}>{l}</div>
                </div>
              ))}
            </div>
          </div>
        </Wrap>
        {/* category quick strip */}
        <Wrap style={{ paddingBottom: 16 }}>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            {CATEGORIES.map((c) => (
              <CatChip key={c.id} cat={c.id} small onClick={() => go("browse", { cat: c.id })} />
            ))}
          </div>
        </Wrap>
      </div>

      {/* featured */}
      <Wrap style={{ paddingTop: 56 }}>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, marginBottom: 26 }}>
          <div>
            <SectionLabel>Open right now</SectionLabel>
            <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(28px,4vw,40px)", letterSpacing: "-0.03em", margin: "12px 0 0", color: "var(--ink)" }}>What people need help with</h2>
          </div>
          <Button variant="ghost" iconRight="arrow" onClick={() => go("browse")}>See all tasks</Button>
        </div>
        <div className="grid-3">
          {featured.map((t) => <TaskCard key={t.id} task={t} onClick={() => openTask(t.id)} />)}
        </div>
      </Wrap>

      <HowItWorks compact go={go} onPost={onPost} />
      <TrustStrip />

      {/* CTA band */}
      <Wrap style={{ paddingTop: 72 }}>
        <div style={{
          background: "var(--ink)", borderRadius: 28, padding: "clamp(36px,5vw,64px)", color: "var(--paper)",
          position: "relative", overflow: "hidden",
        }}>
          <div style={{ position: "relative", zIndex: 1, maxWidth: 600 }}>
            <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(28px,4vw,46px)", letterSpacing: "-0.03em", lineHeight: 1.05, margin: 0 }}>
              Got a free afternoon?<br />Get paid to help.
            </h2>
            <p style={{ fontSize: 17.5, lineHeight: 1.5, color: "color-mix(in srgb, var(--paper) 72%, transparent)", margin: "18px 0 28px", maxWidth: 480 }}>
              Pick up tasks near you, do them well, build a reputation. Cash for paid gigs, good karma for favors.
            </p>
            <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
              <Button size="lg" onClick={() => go("browse")}>Find tasks to do</Button>
              <Button size="lg" variant="ghost" onClick={() => go("how")} style={{ borderColor: "color-mix(in srgb, var(--paper) 30%, transparent)", color: "var(--paper)" }}>How it works</Button>
            </div>
          </div>
          <div style={{ position: "absolute", right: -40, top: -40, width: 320, height: 320, borderRadius: "50%", background: "color-mix(in srgb, var(--clay) 38%, transparent)", filter: "blur(10px)", opacity: 0.5 }} />
        </div>
      </Wrap>
    </div>
  );
}

/* ============ HOW IT WORKS ============ */
function HowItWorks({ compact, go, onPost }) {
  const steps = [
    { icon: "doc", t: "Post your task", d: "Describe what you need, where, and your budget — or mark it a favor. Takes two minutes." },
    { icon: "users", t: "Humans apply", d: "Real, rated people nearby offer to help. Browse their profiles and pick the best fit." },
    { icon: "check", t: "They do the thing", d: "Clear instructions, real-time updates, proof of completion the way you asked for it." },
    { icon: "wallet", t: "Pay when happy", d: "Funds are held safely and only released once the task is done to your satisfaction." },
  ];
  return (
    <Wrap style={{ paddingTop: compact ? 80 : 56 }}>
      {!compact && (
        <button onClick={() => go("home")} style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600, padding: "8px 0", marginBottom: 12 }}>
          <Icon name="back" size={17} /> Back to home
        </button>
      )}
      <div style={{ textAlign: compact ? "center" : "left", marginBottom: 34 }}>
        <div style={{ display: "flex", justifyContent: compact ? "center" : "flex-start" }}><SectionLabel>How it works</SectionLabel></div>
        <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(28px,4vw,42px)", letterSpacing: "-0.03em", margin: "12px 0 0", color: "var(--ink)" }}>Four steps, real results</h2>
      </div>
      <div className="grid-4">
        {steps.map((s, i) => (
          <div key={s.t} style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 18, padding: 24 }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
              <span style={{ width: 46, height: 46, borderRadius: 13, background: "var(--ink-3)", display: "grid", placeItems: "center", color: "var(--clay)" }}>
                <Icon name={s.icon} size={24} stroke={1.8} />
              </span>
              <span style={{ fontFamily: "var(--display)", fontSize: 38, fontWeight: 700, color: "var(--line-dk)", lineHeight: 1 }}>{i + 1}</span>
            </div>
            <h3 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 20, letterSpacing: "-0.02em", margin: "0 0 8px", color: "var(--ink)" }}>{s.t}</h3>
            <p style={{ fontSize: 14.5, lineHeight: 1.5, color: "var(--ink-2)", margin: 0 }}>{s.d}</p>
          </div>
        ))}
      </div>
      {!compact && (
        <div style={{ display: "flex", justifyContent: "center", marginTop: 40 }}>
          <Button size="lg" icon="plus" onClick={onPost}>Post your first task</Button>
        </div>
      )}
    </Wrap>
  );
}

/* ============ TRUST STRIP ============ */
function TrustStrip() {
  const items = [
    { icon: "wallet", t: "Secure payments", d: "Funds held until the task is done" },
    { icon: "shield", t: "Verified humans", d: "ID-checked, with a blue tick" },
    { icon: "star", t: "Ratings & reviews", d: "See history before you hire" },
    { icon: "chat", t: "Direct messaging", d: "Talk it through before you commit" },
  ];
  return (
    <Wrap style={{ paddingTop: 80 }}>
      <div style={{ background: "var(--green-3)", border: "1px solid color-mix(in srgb, var(--green) 22%, transparent)", borderRadius: 24, padding: "clamp(28px,4vw,40px)" }}>
        <div className="grid-4" style={{ gap: 28 }}>
          {items.map((it) => (
            <div key={it.t} style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
              <span style={{ color: "var(--green)", flexShrink: 0, marginTop: 2 }}><Icon name={it.icon} size={26} stroke={1.8} /></span>
              <div>
                <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 18, letterSpacing: "-0.02em", color: "var(--ink)" }}>{it.t}</div>
                <div style={{ fontSize: 13.8, color: "var(--ink-2)", marginTop: 3, lineHeight: 1.4 }}>{it.d}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </Wrap>
  );
}

/* ============ BROWSE ============ */
function Browse({ go, openTask, tasks, initialCat, saved, toggleSave, userCity }) {
  const [cat, setCat] = useS1(initialCat || "all");
  const [q, setQ] = useS1("");
  const [pay, setPay] = useS1("all"); // all | paid | favor
  const [sort, setSort] = useS1("recent");
  const [near, setNear] = useS1(false);
  const cityNorm = (userCity || "").trim().toLowerCase();

  let list = tasks.filter((t) => {
    if (isTaskExpired(t)) return false;                    // hide tasks past their deadline
    if (near && cityNorm && !t.remote && (t.city || "").trim().toLowerCase() !== cityNorm) return false;
    if (cat !== "all" && t.cat !== cat) return false;
    if (pay === "paid" && t.pay.kind !== "fixed") return false;
    if (pay === "favor" && t.pay.kind !== "favor") return false;
    if (q && !(t.title + " " + t.blurb + " " + t.city).toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });
  if (sort === "pay") {
    const RATE = { "₹": 1, "$": 85, "€": 92, "£": 107 };
    const toInr = (p) => p.kind === "favor" ? -1 : (p.amount || 0) * (RATE[p.cur] || 1);
    list = [...list].sort((a, b) => toInr(b.pay) - toInr(a.pay));
  }

  return (
    <Wrap style={{ paddingTop: 36, paddingBottom: 20 }}>
      <button onClick={() => go("home")} style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600, padding: "8px 0", marginBottom: 8 }}>
        <Icon name="back" size={17} /> Back to home
      </button>
      <h1 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(30px,4vw,44px)", letterSpacing: "-0.03em", margin: 0, color: "var(--ink)" }}>Browse tasks</h1>
      <p style={{ fontSize: 16.5, color: "var(--ink-2)", margin: "8px 0 24px" }}>{list.length} open task{list.length !== 1 ? "s" : ""} waiting for a human.</p>

      {/* search + controls */}
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 18 }}>
        <div style={{ flex: "1 1 280px", position: "relative", display: "flex", alignItems: "center" }}>
          <span style={{ position: "absolute", left: 16, color: "var(--ink-2)" }}><Icon name="search" size={19} /></span>
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search tasks, places…"
            style={{ width: "100%", padding: "13px 16px 13px 44px", borderRadius: 12, border: "1px solid var(--line)", background: "var(--surface)", fontFamily: "var(--sans)", fontSize: 15.5, color: "var(--ink)", outline: "none" }} />
        </div>
        <div style={{ display: "inline-flex", background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 12, padding: 4 }}>
          {[["all", "All"], ["paid", "Paid"], ["favor", "Favors"]].map(([v, l]) => (
            <button key={v} onClick={() => setPay(v)} style={{
              padding: "9px 16px", borderRadius: 9, border: "none", cursor: "pointer", fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600,
              background: pay === v ? "var(--ink)" : "transparent", color: pay === v ? "var(--paper)" : "var(--ink-2)",
            }}>{l}</button>
          ))}
        </div>
        {cityNorm && (
          <button onClick={() => setNear((n) => !n)} title={`Tasks in ${userCity}`} style={{
            display: "inline-flex", alignItems: "center", gap: 7, padding: "0 16px", borderRadius: 12, cursor: "pointer",
            border: "1px solid " + (near ? "var(--clay)" : "var(--line)"),
            background: near ? "var(--clay)" : "var(--surface)", color: near ? "#fff" : "var(--ink-2)",
            fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600,
          }}>
            <Icon name="pin" size={16} /> Near me
          </button>
        )}
        <select value={sort} onChange={(e) => setSort(e.target.value)} style={{
          padding: "0 16px", borderRadius: 12, border: "1px solid var(--line)", background: "var(--surface)", fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600, color: "var(--ink)", cursor: "pointer",
        }}>
          <option value="recent">Most recent</option>
          <option value="pay">Highest pay</option>
        </select>
      </div>

      {/* category chips */}
      <div style={{ display: "flex", gap: 9, flexWrap: "wrap", marginBottom: 28 }}>
        <CatChipAll active={cat === "all"} onClick={() => setCat("all")} />
        {CATEGORIES.map((c) => <CatChip key={c.id} cat={c.id} small active={cat === c.id} onClick={() => setCat(c.id)} />)}
      </div>

      {list.length === 0 ? (
        <div style={{ textAlign: "center", padding: "80px 20px", color: "var(--ink-2)" }}>
          <Icon name="search" size={40} stroke={1.4} />
          <p style={{ fontSize: 18, fontWeight: 600, color: "var(--ink)", margin: "14px 0 4px" }}>No tasks match that.</p>
          <p style={{ margin: 0 }}>Try a different category or clear your search.</p>
        </div>
      ) : (
        <div className="grid-3">
          {list.map((t) => <TaskCard key={t.id} task={t} onClick={() => openTask(t.id)} />)}
        </div>
      )}
    </Wrap>
  );
}

function CatChipAll({ active, onClick }) {
  return (
    <button onClick={onClick} style={{
      display: "inline-flex", alignItems: "center", gap: 7, cursor: "pointer", padding: "7px 15px", borderRadius: 999,
      fontFamily: "var(--sans)", fontSize: 13.5, fontWeight: 600, whiteSpace: "nowrap",
      background: active ? "var(--ink)" : "var(--surface)", color: active ? "var(--paper)" : "var(--ink)",
      border: "1px solid " + (active ? "var(--ink)" : "var(--line)"),
    }}><Icon name="bolt" size={14} stroke={1.8} /> All tasks</button>
  );
}

Object.assign(window, { Landing, HowItWorks, TrustStrip, Browse, Wrap, SectionLabel });
