// screens-post.jsx — Post a task (multi-step) + Dashboard + Saved
const { useState: useS3 } = React;

const CUR_OPTS = ["₹", "$", "€", "£"];

function PostTask({ go, onPublish, userEmail, userName }) {
  const [step, setStep] = useS3(0);
  const [d, setD] = useS3({
    cat: "", title: "", city: "Hyderabad", remote: false,
    blurb: "", details: ["", "", ""], proof: "", deadline: "",
    kind: "fixed", amount: "", cur: "₹", favorNote: "", urgent: false,
  });
  const [paying, setPaying] = useS3(false);
  const [payError, setPayError] = useS3("");
  const set = (k, v) => setD((s) => ({ ...s, [k]: v }));
  const steps = ["Category", "Details", "Budget", "Review"];
  const nowLocal = new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 16);  // for deadline min

  const canNext = () => {
    if (step === 0) return !!d.cat;
    if (step === 1) return d.title.trim().length > 4 && d.blurb.trim().length > 10;
    if (step === 2) return d.kind === "favor" ? true : Number(d.amount) >= 10;
    return true;
  };

  // tells the user exactly what's missing on the current step
  const nextHint = () => {
    if (step === 1) {
      if (d.title.trim().length <= 4) return "Add a task title (at least 5 characters).";
      if (d.blurb.trim().length <= 10) return "Add a description — at least a sentence about what's needed.";
    }
    if (step === 2 && d.kind !== "favor" && !(Number(d.amount) > 0)) return "Enter a budget amount above 0.";
    return "";
  };

  const isPaid = d.kind === "fixed" && Number(d.amount) > 0;
  const taskAmount = Number(d.amount) || 0;
  const commissionRate = window.PLATFORM_COMMISSION || 10;
  const commissionAmount = isPaid ? Math.round(taskAmount * commissionRate) / 100 : 0;
  const workerGets = isPaid ? taskAmount - commissionAmount : 0;

  const publish = async () => {
    const fields = { ...d, title: d.title.trim(), blurb: d.blurb.trim(), proof: d.proof.trim() };

    if (!isPaid) {
      // favor task — publish directly, no payment needed
      onPublish(fields);
      return;
    }

    // paid task — collect payment via Razorpay first
    setPaying(true);
    setPayError("");

    try {
      // Step 1: Create Razorpay order
      const { data: orderData, error: orderError } = await Payments.createOrder(
        "pending_" + Date.now(), // temporary ID — real ID assigned after DB insert
        taskAmount,
        d.cur === "₹" ? "INR" : d.cur === "$" ? "USD" : d.cur === "€" ? "EUR" : d.cur === "£" ? "GBP" : "INR"
      );

      if (orderError) {
        setPayError(orderError);
        setPaying(false);
        return;
      }

      // If in demo mode (mock = true), skip Razorpay Checkout
      if (orderData.mock) {
        onPublish(fields);
        setPaying(false);
        return;
      }

      // Step 2: Open Razorpay Checkout
      Payments.openCheckout(
        {
          orderId: orderData.order_id,
          amount: taskAmount,
          currency: orderData.currency || "INR",
          taskTitle: d.title.trim(),
          userEmail: userEmail || "",
          userName: userName || "",
        },
        async (paymentResponse) => {
          // Step 3: Verify payment signature
          const { error: verifyError } = await Payments.verifyPayment(
            "pending", // will be linked after task creation
            paymentResponse.razorpay_payment_id,
            paymentResponse.razorpay_order_id,
            paymentResponse.razorpay_signature
          );

          if (verifyError) {
            setPayError("Payment verification failed: " + verifyError);
            setPaying(false);
            return;
          }

          // Step 4: Publish the task (payment confirmed!)
          fields._razorpay = {
            order_id: paymentResponse.razorpay_order_id,
            payment_id: paymentResponse.razorpay_payment_id,
          };
          onPublish(fields);
          setPaying(false);
        },
        (failureMsg) => {
          setPayError(failureMsg || "Payment was cancelled or failed.");
          setPaying(false);
        }
      );
    } catch (e) {
      setPayError(String(e.message || e));
      setPaying(false);
    }
  };

  return (
    <Wrap style={{ paddingTop: 28, paddingBottom: 20, maxWidth: 760 }}>
      <button onClick={() => (step === 0 ? go("home") : setStep(step - 1))} 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} /> {step === 0 ? "Cancel" : "Back"}
      </button>

      {/* stepper */}
      <div style={{ display: "flex", gap: 8, marginBottom: 30 }}>
        {steps.map((s, i) => (
          <div key={s} style={{ flex: 1 }}>
            <div style={{ height: 5, borderRadius: 999, background: i <= step ? "var(--clay)" : "var(--line)", transition: "background .25s" }} />
            <div style={{ fontSize: 12.5, fontWeight: 600, marginTop: 8, color: i <= step ? "var(--ink)" : "var(--ink-2)" }}>{s}</div>
          </div>
        ))}
      </div>

      {step === 0 && (
        <div>
          <StepHead t="What kind of task is it?" s="Pick the category that fits best." />
          <div className="grid-3" style={{ gridTemplateColumns: "repeat(auto-fill,minmax(200px,1fr))" }}>
            {CATEGORIES.map((c) => (
              <button key={c.id} onClick={() => { set("cat", c.id); setStep(1); }} style={{
                textAlign: "left", cursor: "pointer", background: d.cat === c.id ? "var(--ink)" : "var(--surface)",
                color: d.cat === c.id ? "var(--paper)" : "var(--ink)", border: "1px solid " + (d.cat === c.id ? "var(--ink)" : "var(--line)"),
                borderRadius: 16, padding: 20, display: "flex", flexDirection: "column", gap: 14, transition: "all .15s",
              }}>
                <span style={{ width: 44, height: 44, borderRadius: 12, background: d.cat === c.id ? "color-mix(in srgb, var(--paper) 16%, transparent)" : "var(--ink-3)", color: d.cat === c.id ? "var(--paper)" : "var(--clay)", display: "grid", placeItems: "center" }}>
                  <Icon name={c.icon} size={24} stroke={1.8} />
                </span>
                <span style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 17.5, letterSpacing: "-0.02em" }}>{c.label}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      {step === 1 && (
        <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
          <StepHead t="Tell us the details" s="The clearer you are, the better the applicants." />
          <Field label="Task title (required)">
            <input value={d.title} onChange={(e) => set("title", e.target.value.slice(0, 100))} placeholder="e.g. Check iPad Pro stock at the Apple Store" maxLength={100} style={inputStyle} />
            <div style={{ fontSize: 12.5, color: d.title.trim().length > 0 && d.title.trim().length <= 4 ? "var(--clay)" : "var(--ink-2)", marginTop: 6 }}>{d.title.length > 0 ? `${d.title.trim().length}/100 characters${d.title.trim().length <= 4 ? " — need at least 5" : ""}` : "Min 5 characters"}</div>
          </Field>
          <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
            <div style={{ flex: "1 1 220px" }}>
              <Field label="Location"><input value={d.city} onChange={(e) => set("city", e.target.value)} placeholder="City" disabled={d.remote} style={{ ...inputStyle, opacity: d.remote ? 0.5 : 1 }} /></Field>
            </div>
            <label style={{ display: "flex", alignItems: "center", gap: 9, paddingBottom: 12, cursor: "pointer", alignSelf: "flex-end" }}>
              <span onClick={() => set("remote", !d.remote)} style={{ width: 44, height: 26, borderRadius: 999, background: d.remote ? "var(--clay)" : "var(--line-dk)", position: "relative", transition: "background .2s" }}>
                <span style={{ position: "absolute", top: 3, left: d.remote ? 21 : 3, width: 20, height: 20, borderRadius: "50%", background: "#fff", transition: "left .2s" }} />
              </span>
              <span style={{ fontSize: 14.5, fontWeight: 600, color: "var(--ink)" }}>Can be done remotely</span>
            </label>
          </div>
          <Field label="Description (required)" hint="What needs doing and why? At least a sentence.">
            <textarea value={d.blurb} onChange={(e) => set("blurb", e.target.value.slice(0, 500))} rows={3} maxLength={500} placeholder="Drop by the store and check if the latest iPad Pro is in stock…" style={{ ...inputStyle, resize: "vertical", lineHeight: 1.5 }} />
            <div style={{ fontSize: 12.5, color: d.blurb.trim().length > 0 && d.blurb.trim().length <= 10 ? "var(--clay)" : "var(--ink-2)", marginTop: 6 }}>{d.blurb.length > 0 ? `${d.blurb.trim().length}/500 characters${d.blurb.trim().length <= 10 ? " — need at least 10" : ""}` : "Min 10 characters"}</div>
          </Field>
          <Field label="Step-by-step (optional)" hint="Add the key things they should do.">
            <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
              {d.details.map((v, i) => (
                <input key={i} value={v} onChange={(e) => { const n = [...d.details]; n[i] = e.target.value; set("details", n); }} placeholder={`Step ${i + 1}`} style={inputStyle} />
              ))}
              <button onClick={() => set("details", [...d.details, ""])} style={{ alignSelf: "flex-start", background: "none", border: "none", color: "var(--clay)", fontWeight: 600, fontFamily: "var(--sans)", fontSize: 14, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 5, padding: "4px 0" }}>
                <Icon name="plus" size={15} /> Add a step
              </button>
            </div>
          </Field>
          <Field label="Proof of completion (optional)" hint="What should they send to prove it's done?">
            <input value={d.proof} onChange={(e) => set("proof", e.target.value)} placeholder="e.g. Photos of the display + price cards" style={inputStyle} />
          </Field>
          <Field label="Deadline (optional)" hint="When does this need to be done by?">
            <input type="datetime-local" value={d.deadline} min={nowLocal} onChange={(e) => set("deadline", e.target.value)} style={{ ...inputStyle, maxWidth: 280, cursor: "pointer" }} />
          </Field>
        </div>
      )}

      {step === 2 && (
        <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
          <StepHead t="How are you paying?" s="A fixed price, or just a friendly favor." />
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
            {[["fixed", "wallet", "Fixed price", "Set a budget and pay on completion"], ["favor", "heart", "It's a favor", "No money — good karma or a small thank-you"]].map(([v, ic, t, s]) => (
              <button key={v} onClick={() => set("kind", v)} style={{
                flex: "1 1 220px", textAlign: "left", cursor: "pointer", borderRadius: 16, padding: 20, display: "flex", gap: 14, alignItems: "flex-start",
                border: "1.5px solid " + (d.kind === v ? "var(--clay)" : "var(--line)"), background: d.kind === v ? "color-mix(in srgb, var(--clay) 7%, var(--surface))" : "var(--surface)",
              }}>
                <span style={{ color: d.kind === v ? "var(--clay)" : "var(--ink-2)", marginTop: 2 }}><Icon name={ic} size={24} stroke={1.8} /></span>
                <span>
                  <span style={{ display: "block", fontFamily: "var(--display)", fontWeight: 600, fontSize: 18, letterSpacing: "-0.02em", color: "var(--ink)" }}>{t}</span>
                  <span style={{ display: "block", fontSize: 13.5, color: "var(--ink-2)", marginTop: 4, lineHeight: 1.4 }}>{s}</span>
                </span>
              </button>
            ))}
          </div>

          {d.kind === "fixed" ? (
            <Field label="Budget">
              <div style={{ display: "flex", gap: 10 }}>
                <select value={d.cur} onChange={(e) => set("cur", e.target.value)} style={{ ...inputStyle, width: "auto", fontWeight: 700, cursor: "pointer" }}>
                  {CUR_OPTS.map((c) => <option key={c} value={c}>{c}</option>)}
                </select>
                <input value={d.amount} onChange={(e) => set("amount", e.target.value.replace(/[^\d]/g, "").slice(0, 7))} inputMode="numeric" placeholder="600" maxLength={7} style={{ ...inputStyle, fontWeight: 700, fontSize: 18, maxWidth: 220 }} />
              </div>
              <div style={{ fontSize: 12.5, color: d.amount && Number(d.amount) > 0 && Number(d.amount) < 10 ? "var(--clay)" : "var(--ink-2)", marginTop: 6 }}>{d.amount && Number(d.amount) > 0 ? (Number(d.amount) < 10 ? "Minimum budget is ₹10" : `₹${Number(d.amount).toLocaleString("en-IN")}`) : "Enter amount in whole numbers"}</div>
            </Field>
          ) : (
            <Field label="Thank-you note (optional)" hint="Coffee, pizza, a future favor…">
              <input value={d.favorNote} onChange={(e) => set("favorNote", e.target.value)} placeholder="Coffee's on me ☕" style={inputStyle} />
            </Field>
          )}

          <label style={{ display: "flex", alignItems: "center", gap: 11, cursor: "pointer" }}>
            <span onClick={() => set("urgent", !d.urgent)} style={{ width: 44, height: 26, borderRadius: 999, background: d.urgent ? "var(--clay)" : "var(--line-dk)", position: "relative", transition: "background .2s", flexShrink: 0 }}>
              <span style={{ position: "absolute", top: 3, left: d.urgent ? 21 : 3, width: 20, height: 20, borderRadius: "50%", background: "#fff", transition: "left .2s" }} />
            </span>
            <span>
              <span style={{ fontSize: 15, fontWeight: 600, color: "var(--ink)" }}>Mark as urgent</span>
              <span style={{ display: "block", fontSize: 13, color: "var(--ink-2)" }}>Pushes your task to the top and flags it for fast response.</span>
            </span>
          </label>
        </div>
      )}

      {step === 3 && (
        <div>
          <StepHead t="Looking good?" s="Here's how humans will see your task." />
          <div style={{ maxWidth: 380, margin: "0 auto 24px" }}>
            <TaskCard task={previewTask(d)} onClick={() => {}} />
          </div>

          {/* Payment breakdown for paid tasks */}
          {isPaid && (
            <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 16, padding: "20px 22px", marginBottom: 20, maxWidth: 380, marginLeft: "auto", marginRight: "auto" }}>
              <div style={{ fontSize: 12.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-2)", marginBottom: 14, display: "flex", alignItems: "center", gap: 7 }}>
                <Icon name="wallet" size={14} /> Payment breakdown
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 15, color: "var(--ink)" }}>
                  <span>Task budget</span>
                  <span style={{ fontWeight: 700 }}>{d.cur}{taskAmount.toLocaleString()}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, color: "var(--ink-2)" }}>
                  <span>Platform fee ({commissionRate}%)</span>
                  <span>−{d.cur}{commissionAmount.toLocaleString()}</span>
                </div>
                <div style={{ height: 1, background: "var(--line)", margin: "4px 0" }} />
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 15.5, color: "var(--green)", fontWeight: 700 }}>
                  <span>Worker receives</span>
                  <span>{d.cur}{workerGets.toLocaleString()}</span>
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 14, fontSize: 12.5, color: "var(--ink-2)" }}>
                <Icon name="shield" size={13} /> You pay {d.cur}{taskAmount.toLocaleString()} · held safely until task is done
              </div>
            </div>
          )}

          {/* Payment error */}
          {payError && (
            <div style={{ maxWidth: 380, margin: "0 auto 16px", display: "flex", alignItems: "center", gap: 8, padding: "12px 14px", borderRadius: 12, background: "color-mix(in srgb, var(--clay) 10%, transparent)", color: "var(--clay)", fontSize: 14, fontWeight: 600 }}>
              <Icon name="bolt" size={15} /> {payError}
            </div>
          )}
        </div>
      )}

      {step > 0 && step < 3 && !canNext() && nextHint() && (
        <div style={{ marginTop: 24, display: "flex", alignItems: "center", gap: 8, justifyContent: "flex-end", color: "var(--amber-dk)", fontSize: 14, fontWeight: 600 }}>
          <Icon name="bolt" size={15} /> {nextHint()}
        </div>
      )}

      {step > 0 && (
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: step < 3 && !canNext() && nextHint() ? 12 : 32 }}>
          {step < 3 && <Button size="lg" iconRight="arrow" disabled={!canNext()} onClick={() => setStep(step + 1)}>Continue</Button>}
          {step === 3 && (
            <Button size="lg" icon={isPaid ? "wallet" : "check"} onClick={publish} disabled={paying}>
              {paying ? "Processing payment…" : isPaid ? `Pay ${d.cur}${taskAmount.toLocaleString()} & publish` : "Publish task"}
            </Button>
          )}
        </div>
      )}
    </Wrap>
  );
}

function previewTask(d) {
  return {
    id: "preview", cat: d.cat || "errands", poster: "__me", title: d.title || "Your task title",
    city: d.city, remote: d.remote, posted: "just now", applicants: 0, urgent: d.urgent, deadline: d.deadline || null,
    pay: d.kind === "favor" ? { kind: "favor", note: d.favorNote } : { kind: "fixed", amount: Number(d.amount) || 0, cur: d.cur },
  };
}

function StepHead({ t, s }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <h1 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(26px,3.5vw,36px)", letterSpacing: "-0.03em", margin: 0, color: "var(--ink)" }}>{t}</h1>
      <p style={{ fontSize: 16.5, color: "var(--ink-2)", margin: "8px 0 0" }}>{s}</p>
    </div>
  );
}

/* ===== DASHBOARD ===== */
function Dashboard({ go, openTask, posted, applications, allTasks, taskMeta, getMeta, saved, toggleSave, profile, canLogout, onLogout, walletBalance, walletCur }) {
  const [tab, setS3] = useS3("posted");
  const me = profile || ME;
  const appTasks = applications
    .map((a) => ({ ...a, task: allTasks.find((t) => t.id === a.taskId) }))
    .filter((a) => a.task);
  const savedTasks = allTasks.filter((t) => saved.has(t.id));

  const tabs = [
    ["posted", "Posted", posted.length],
    ["doing",  "I'm doing", appTasks.length],
    ["saved",  "Saved", savedTasks.length],
  ];

  return (
    <Wrap style={{ paddingTop: 28, 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: 12 }}>
        <Icon name="back" size={17} /> Back to home
      </button>
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 8 }}>
        <Avatar name={me.name === "You" ? "You Me" : me.name} size={52} src={me.avatarUrl} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <h1 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(26px,3.5vw,38px)", letterSpacing: "-0.03em", margin: 0, color: "var(--ink)" }}>My tasks</h1>
          <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 14, color: "var(--ink-2)", marginTop: 2, flexWrap: "wrap" }}>
            <Stars value={me.rating || 0} /> · <span>{me.city || "—"}</span>
            {me.verified && <><span>·</span> <VerifiedTick size={14} /> Verified</>}
          </div>
        </div>
        {canLogout && (
          <Button size="sm" variant="ghost" icon="back" onClick={onLogout}>Log out</Button>
        )}
      </div>

      {/* Wallet balance widget */}
      {walletBalance !== undefined && (
        <button onClick={() => go("wallet")} style={{
          width: "100%", textAlign: "left", cursor: "pointer", margin: "18px 0 0",
          background: "linear-gradient(135deg, var(--ink) 0%, color-mix(in srgb, var(--ink) 80%, var(--clay)) 100%)",
          border: "none", borderRadius: 16, padding: "18px 22px", display: "flex", alignItems: "center", gap: 16,
          color: "#fff", boxShadow: "0 8px 28px -10px rgba(30,20,10,.4)",
        }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: "rgba(255,255,255,.12)", display: "grid", placeItems: "center", flexShrink: 0 }}>
            <Icon name="wallet" size={22} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.06em", opacity: 0.7 }}>Wallet balance</div>
            <div style={{ fontFamily: "var(--display)", fontSize: 26, fontWeight: 700, letterSpacing: "-0.02em", marginTop: 2 }}>
              {walletCur || "₹"}{Number(walletBalance || 0).toLocaleString()}
            </div>
          </div>
          <div style={{ fontSize: 13, fontWeight: 600, opacity: 0.8, display: "flex", alignItems: "center", gap: 5 }}>
            View <Icon name="arrow" size={14} />
          </div>
        </button>
      )}

      <div style={{ overflowX: "auto", WebkitOverflowScrolling: "touch", margin: "22px 0 26px" }}>
      <div style={{ display: "inline-flex", gap: 4, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 12, padding: 4, whiteSpace: "nowrap" }}>
        {tabs.map(([v, l, n]) => (
          <button key={v} onClick={() => setS3(v)} style={{
            padding: "10px 18px", borderRadius: 9, border: "none", cursor: "pointer", fontFamily: "var(--sans)", fontSize: 15, fontWeight: 600,
            display: "inline-flex", alignItems: "center", gap: 8,
            background: tab === v ? "var(--ink)" : "transparent", color: tab === v ? "var(--paper)" : "var(--ink-2)",
          }}>
            {l}
            <span style={{ fontSize: 12.5, fontWeight: 700, padding: "1px 8px", borderRadius: 999, background: tab === v ? "color-mix(in srgb, var(--paper) 22%, transparent)" : "var(--ink-3)", color: tab === v ? "var(--paper)" : "var(--ink-2)" }}>{n}</span>
          </button>
        ))}
      </div>
      </div>

      {/* POSTED TAB */}
      {tab === "posted" && (
        posted.length === 0 ? (
          <Empty icon="doc" t="No tasks posted yet" s="Post your first task and watch the humans roll in." cta="Post a task" onCta={() => go("post")} />
        ) : (
          <div className="grid-3">
            {posted.map((t) => {
              const meta = getMeta(t.id);
              return (
                <div key={t.id} style={{ position: "relative" }}>
                  <div style={{ position: "absolute", top: 14, right: 14, zIndex: 2 }}>
                    <StatusPill status={meta.status || "open"} />
                  </div>
                  <TaskCard task={t} onClick={() => openTask(t.id)} />
                </div>
              );
            })}
          </div>
        )
      )}

      {/* DOING TAB */}
      {tab === "doing" && (
        appTasks.length === 0 ? (
          <Empty icon="bolt" t="You haven't applied to anything yet" s="Browse open tasks and send your first application." cta="Browse tasks" onCta={() => go("browse")} />
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            {appTasks.map(({ task, msg, price, when }) => {
              const meta = getMeta(task.id);
              const isAssigned = meta.status === "assigned" && meta.assignedTo === "__me";
              const isProof = meta.status === "proof_submitted" && meta.assignedTo === "__me";
              const isDone = meta.status === "completed";
              return (
                <button key={task.id} onClick={() => openTask(task.id)} style={{ textAlign: "left", cursor: "pointer", background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 16, padding: 20, display: "flex", gap: 18, alignItems: "center", flexWrap: "wrap" }}>
                  <div style={{ flex: "1 1 260px", minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-2)", textTransform: "uppercase", letterSpacing: "0.04em", marginBottom: 6 }}>{CAT[task.cat].label}</div>
                    <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 19, letterSpacing: "-0.02em", color: "var(--ink)", lineHeight: 1.2 }}>{task.title}</div>
                    <div style={{ fontSize: 14, color: "var(--ink-2)", marginTop: 8, lineHeight: 1.4, overflow: "hidden", display: "-webkit-box", WebkitLineClamp: 1, WebkitBoxOrient: "vertical" }}>"{msg}"</div>
                  </div>
                  <div style={{ textAlign: "right", flexShrink: 0 }}>
                    {isDone ? (
                      <div style={{ fontSize: 12, fontWeight: 700, color: "var(--green)", background: "var(--green-3)", padding: "5px 11px", borderRadius: 999, display: "inline-flex", alignItems: "center", gap: 5, marginBottom: 10 }}>
                        <Icon name="check" size={12} stroke={2.5} /> Completed
                      </div>
                    ) : isProof ? (
                      <div style={{ fontSize: 12, fontWeight: 700, color: "var(--amber-dk)", background: "color-mix(in srgb, var(--amber) 18%, transparent)", padding: "5px 11px", borderRadius: 999, display: "inline-block", marginBottom: 10 }}>Awaiting payment</div>
                    ) : isAssigned ? (
                      <div style={{ fontSize: 12, fontWeight: 700, color: "var(--blue)", background: "color-mix(in srgb, var(--blue) 12%, transparent)", padding: "5px 11px", borderRadius: 999, display: "inline-flex", alignItems: "center", gap: 5, marginBottom: 10 }}>
                        <Icon name="bolt" size={12} fill stroke={0} /> You're on it
                      </div>
                    ) : (
                      <div style={{ fontSize: 12, fontWeight: 700, color: "var(--amber-dk)", background: "color-mix(in srgb, var(--amber) 18%, transparent)", padding: "5px 11px", borderRadius: 999, display: "inline-block", marginBottom: 10 }}>Awaiting reply</div>
                    )}
                    <div>{price ? <PayTag pay={{ kind: "fixed", amount: price, cur: task.pay.cur || "₹" }} /> : <PayTag pay={{ kind: "favor" }} />}</div>
                  </div>
                </button>
              );
            })}
          </div>
        )
      )}

      {/* SAVED TAB */}
      {tab === "saved" && (
        savedTasks.length === 0 ? (
          <Empty icon="heart" t="Nothing saved yet" s="Tap the heart on any task to save it for later." cta="Browse tasks" onCta={() => go("browse")} />
        ) : (
          <div className="grid-3">
            {savedTasks.map((t) => (
              <TaskCard key={t.id} task={t} onClick={() => openTask(t.id)} saved={saved.has(t.id)} onSave={toggleSave} />
            ))}
          </div>
        )
      )}
    </Wrap>
  );
}

function StatusPill({ status }) {
  const map = {
    open:            { label: "Live",       color: "var(--green)",    bg: "var(--green-3)" },
    assigned:        { label: "In progress", color: "var(--amber-dk)", bg: "color-mix(in srgb, var(--amber) 18%, transparent)" },
    proof_submitted: { label: "Proof in",   color: "var(--clay)",     bg: "color-mix(in srgb, var(--clay) 12%, transparent)" },
    completed:       { label: "Done",       color: "var(--green)",    bg: "var(--green-3)" },
    cancelled:       { label: "Cancelled",  color: "var(--ink-2)",    bg: "var(--ink-3)" },
  };
  const s = map[status] || map.open;
  return (
    <span style={{ fontSize: 11.5, fontWeight: 700, color: s.color, background: s.bg, padding: "4px 10px", borderRadius: 999, display: "inline-flex", alignItems: "center", gap: 5 }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: s.color }} /> {s.label}
    </span>
  );
}

function Empty({ icon, t, s, cta, onCta }) {
  return (
    <div style={{ textAlign: "center", padding: "70px 20px", background: "var(--surface)", border: "1px dashed var(--line-dk)", borderRadius: 20 }}>
      <span style={{ color: "var(--ink-2)" }}><Icon name={icon} size={42} stroke={1.4} /></span>
      <p style={{ fontFamily: "var(--display)", fontSize: 22, fontWeight: 600, color: "var(--ink)", margin: "14px 0 6px", letterSpacing: "-0.02em" }}>{t}</p>
      <p style={{ margin: "0 0 22px", color: "var(--ink-2)", fontSize: 15.5 }}>{s}</p>
      <div style={{ display: "flex", justifyContent: "center" }}><Button icon="plus" onClick={onCta}>{cta}</Button></div>
    </div>
  );
}

/* ===== SAVED TASKS PAGE ===== */
function SavedTasks({ go, openTask, tasks, saved, toggleSave }) {
  return (
    <Wrap style={{ paddingTop: 28, 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: 12 }}>
        <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)" }}>Saved tasks</h1>
      <p style={{ fontSize: 16.5, color: "var(--ink-2)", margin: "8px 0 28px" }}>
        {tasks.length} task{tasks.length !== 1 ? "s" : ""} saved.
      </p>
      {tasks.length === 0 ? (
        <Empty icon="heart" t="Nothing saved yet" s="Tap the heart on any task card to save it for later." cta="Browse tasks" onCta={() => go("browse")} />
      ) : (
        <div className="grid-3">
          {tasks.map((t) => (
            <TaskCard key={t.id} task={t} onClick={() => openTask(t.id)} saved={saved.has(t.id)} onSave={toggleSave} />
          ))}
        </div>
      )}
    </Wrap>
  );
}

Object.assign(window, { PostTask, Dashboard, SavedTasks, StatusPill, Empty, StepHead });
