// screens-manage.jsx — applicant management, proof, reviews, messaging
const { useState: useS4 } = React;

const cancelLink = { display: "block", width: "100%", marginTop: 12, background: "none", border: "none", cursor: "pointer", color: "var(--clay)", fontFamily: "var(--sans)", fontSize: 13.5, fontWeight: 600, textAlign: "center", padding: "8px 0" };

/* ===== POSTER'S MANAGEMENT SIDEBAR ===== */
function ManageTask({ task, meta, taskApplicants, onAccept, onReject, onRelease, onReview, onMessage, onBoost, onCancel, onEdit }) {
  const [showRelease, setShowRelease] = useS4(false);
  const [showReview, setShowReview] = useS4(false);
  const [showBoost, setShowBoost] = useS4(false);
  const [showCancel, setShowCancel] = useS4(false);
  const [showEdit, setShowEdit] = useS4(false);
  const [showReport, setShowReport] = useS4(false);
  const status = meta?.status || "open";
  const isFavor = task.pay.kind === "favor";
  const apps = (taskApplicants || []).filter((a) => a.status !== "rejected");
  const pending = apps.filter((a) => a.status === "pending");
  const assignedPerson = meta?.assignedTo ? (PEOPLE[meta.assignedTo] || meta.workerProfile || { name: "Assigned worker", city: "", rating: 0, jobs: 0, verified: false }) : null;

  const handleReport = (reason) => {
    ADMIN_STRIKES.push({
      id: "report_" + Date.now(),
      taskId: task.id,
      reporterId: currentUserId,
      reportedId: meta.assignedTo,
      reason,
      status: "pending",
      date: new Date().toISOString()
    });
    setShowReport(false);
    alert("User reported. Admin will review this strike.");
  };

  return (
    <div style={{ position: "sticky", top: 84, display: "flex", flexDirection: "column", gap: 16 }}>
      {/* status card */}
      <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 18, padding: 22, boxShadow: "0 4px 16px -10px rgba(40,30,15,.18)" }}>
        <StatusBadge status={status} />

        {status === "open" && (
          <div style={{ marginTop: 16 }}>
            {task.pay.kind === "fixed" && (
              <div style={{ marginBottom: 4 }}><PayTag pay={task.pay} size="lg" /></div>
            )}
            <p style={{ margin: "14px 0 0", fontSize: 14, color: "var(--ink-2)", lineHeight: 1.5 }}>
              {pending.length === 0
                ? "No applicants yet. Share your task link to get more eyes on it."
                : `${pending.length} application${pending.length !== 1 ? "s" : ""} waiting for your decision.`}
            </p>
            {task.pay.kind === "fixed" && (
              <Button full size="md" variant="ghost" icon="bolt" style={{ marginTop: 14 }} onClick={() => setShowBoost(true)}>Boost budget</Button>
            )}
            {onEdit && <Button full size="md" variant="ghost" icon="edit" style={{ marginTop: 8 }} onClick={() => setShowEdit(true)}>Edit task</Button>}
            <div style={{ marginTop: 14, display: "flex", alignItems: "center", gap: 7, color: "var(--ink-2)", fontSize: 13 }}>
              <Icon name="shield" size={14} /> {isFavor ? "No money involved — this one's a favor 🙌" : "Payment held safely until you release it"}
            </div>
            {onCancel && <button onClick={() => setShowCancel(true)} style={cancelLink}>{isFavor ? "Cancel this task" : "Cancel task & get a refund"}</button>}
          </div>
        )}

        {status === "assigned" && assignedPerson && (
          <div style={{ marginTop: 16 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-2)", marginBottom: 12 }}>Working on it</div>
            <div style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 18 }}>
              <Avatar name={assignedPerson.name} size={46} />
              <div>
                <div style={{ fontWeight: 700, fontSize: 15.5, color: "var(--ink)", display: "flex", alignItems: "center", gap: 6 }}>
                  {assignedPerson.name} {assignedPerson.verified && <VerifiedTick size={14} />}
                </div>
                <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 3 }}>
                  <Stars value={assignedPerson.rating} size={12} /> · {assignedPerson.jobs} tasks
                </div>
              </div>
            </div>
            {assignedPerson.phone && (
              <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 14px", borderRadius: 12, background: "var(--ink-3)", color: "var(--ink)", fontSize: 14.5, fontWeight: 600, marginBottom: 12 }}>
                <Icon name="phone" size={16} /> Phone: <a href={`tel:${assignedPerson.phone}`} style={{ color: "var(--clay)", textDecoration: "underline" }}>{assignedPerson.phone}</a>
              </div>
            )}
            <Button full size="md" icon="check" onClick={() => setShowRelease(true)}>I received the proof</Button>
            <Button full size="md" variant="ghost" icon="chat" style={{ marginTop: 8 }} onClick={() => onMessage(meta.assignedTo)}>
              Message {assignedPerson.name.split(" ")[0]}
            </Button>
            <p style={{ margin: "14px 0 0", fontSize: 13, color: "var(--ink-2)", lineHeight: 1.4 }}>
              Waiting for {assignedPerson.name.split(" ")[0]} to deliver. Once you confirm{isFavor ? " they're done, the task is marked complete." : " receipt, payment is released."}
            </p>
            {onCancel && <button onClick={() => setShowCancel(true)} style={cancelLink}>{isFavor ? "Didn't show? Cancel this task" : "Didn't deliver? Cancel & refund me"}</button>}
          </div>
        )}

        {status === "proof_submitted" && assignedPerson && (
          <div style={{ marginTop: 16 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-2)", marginBottom: 10 }}>Proof submitted</div>
            {assignedPerson.phone && (
              <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 14px", borderRadius: 12, background: "var(--ink-3)", color: "var(--ink)", fontSize: 14.5, fontWeight: 600, marginBottom: 12 }}>
                <Icon name="phone" size={16} /> Phone: <a href={`tel:${assignedPerson.phone}`} style={{ color: "var(--clay)", textDecoration: "underline" }}>{assignedPerson.phone}</a>
              </div>
            )}
            <ProofGallery photos={meta.proofPhotos} />
            {meta.proof && (
              <div style={{ background: "var(--ink-3)", borderRadius: 12, padding: "12px 14px", fontSize: 14, color: "var(--ink)", lineHeight: 1.5, marginBottom: 16 }}>
                "{meta.proof}"
              </div>
            )}
            <Button full size="md" icon={isFavor ? "check" : "wallet"} onClick={() => setShowRelease(true)}>{isFavor ? "Confirm & complete" : "Release payment"}</Button>
            <div style={{ display: "flex", gap: 10, marginTop: 10 }}>
              <Button full size="md" variant="ghost" icon="chat" onClick={() => onMessage(meta.assignedTo)}>
                Message
              </Button>
              <Button full size="md" variant="ghost" icon="ban" style={{ color: "var(--clay)" }} onClick={() => setShowReport(true)}>
                Report Doer
              </Button>
            </div>
            {onCancel && <button onClick={() => setShowCancel(true)} style={cancelLink}>{isFavor ? "Not done right? Cancel task" : "Proof not good enough? Reject & refund"}</button>}
          </div>
        )}

        {status === "completed" && (
          <div style={{ marginTop: 16 }}>
            {assignedPerson?.phone && (
              <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 14px", borderRadius: 12, background: "var(--ink-3)", color: "var(--ink)", fontSize: 14.5, fontWeight: 600, marginBottom: 12 }}>
                <Icon name="phone" size={16} /> Phone: <a href={`tel:${assignedPerson.phone}`} style={{ color: "var(--clay)", textDecoration: "underline" }}>{assignedPerson.phone}</a>
              </div>
            )}
            <ProofGallery photos={meta.proofPhotos} />
            {meta.proof && (
              <div style={{ background: "var(--ink-3)", borderRadius: 12, padding: "12px 14px", fontSize: 14, color: "var(--ink)", lineHeight: 1.5, marginBottom: 16 }}>
                "{meta.proof}"
              </div>
            )}
            {!meta.review ? (
              <>
                <p style={{ margin: "0 0 14px", fontSize: 14, color: "var(--ink-2)", lineHeight: 1.4 }}>
                  Payment released! Leave a review for {assignedPerson?.name.split(" ")[0] || "them"}?
                </p>
                <Button full icon="star" onClick={() => setShowReview(true)}>Leave a review</Button>
              </>
            ) : (
              <div style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--green-3)", borderRadius: 12, padding: "12px 14px", color: "var(--green)", fontSize: 14, fontWeight: 600 }}>
                <Icon name="star" size={16} fill stroke={0} /> You rated {meta.review.stars}★ — thanks!
              </div>
            )}
          </div>
        )}

        {status === "cancelled" && (
          <div style={{ marginTop: 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "14px", borderRadius: 12, background: "var(--ink-3)", color: "var(--ink-2)", fontWeight: 600, fontSize: 14.5 }}>
              <Icon name="ban" size={17} /> {isFavor ? "Task cancelled." : "Task cancelled — payment refunded to you."}
            </div>
            {meta.cancelReason && (
              <p style={{ margin: "12px 0 0", fontSize: 13.5, color: "var(--ink-2)", lineHeight: 1.5 }}>Reason: {meta.cancelReason}</p>
            )}
          </div>
        )}
      </div>

      {/* applicant list — only when open */}
      {status === "open" && apps.length > 0 && (
        <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 18, padding: 22 }}>
          <div style={{ fontSize: 12.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-2)", marginBottom: 16 }}>
            Applicants · {pending.length}
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
            {apps.map((app, i) => (
              <ApplicantRow
                key={app.id}
                app={app}
                cur={task.pay.cur}
                last={i === apps.length - 1}
                onAccept={() => onAccept(app)}
                onReject={() => onReject(app.id)}
                onMessage={() => onMessage(app.handle)}
              />
            ))}
          </div>
        </div>
      )}

      {showRelease && (
        <ProofReleaseModal
          meta={meta}
          isFavor={isFavor}
          task={task}
          onClose={() => setShowRelease(false)}
          onConfirm={(proof) => {
            onRelease(proof);
            setShowRelease(false);
            setTimeout(() => setShowReview(true), 400);
          }}
        />
      )}
      {showReview && meta?.assignedTo && (
        <ReviewModal
          targetName={PEOPLE[meta.assignedTo]?.name || "them"}
          onClose={() => setShowReview(false)}
          onSubmit={(review) => { onReview(review); setShowReview(false); }}
        />
      )}
      {showBoost && (
        <BudgetBoostModal
          task={task}
          onClose={() => setShowBoost(false)}
          onConfirm={(newAmount) => { onBoost && onBoost(newAmount); setShowBoost(false); }}
        />
      )}
      {showCancel && (
        <CancelTaskModal
          status={status}
          workerName={assignedPerson?.name}
          isFavor={isFavor}
          onClose={() => setShowCancel(false)}
          onConfirm={(reason) => { onCancel && onCancel(reason); setShowCancel(false); }}
        />
      )}
      {showEdit && (
        <EditTaskModal
          task={task}
          onClose={() => setShowEdit(false)}
          onSave={(fields) => { onEdit && onEdit(fields); setShowEdit(false); }}
        />
      )}
    </div>
  );
}

/* ===== EDIT TASK MODAL (poster) ===== */
function EditTaskModal({ task, onClose, onSave }) {
  const isPaid = task.pay.kind === "fixed";
  const [title, setTitle] = useS4(task.title || "");
  const [blurb, setBlurb] = useS4(task.blurb || "");
  const [amount, setAmount] = useS4(isPaid ? String(task.pay.amount) : "");
  const [deadline, setDeadline] = useS4(task.deadline ? task.deadline.slice(0, 16) : "");
  const [urgent, setUrgent] = useS4(!!task.urgent);
  const [busy, setBusy] = useS4(false);
  const nowLocal = new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 16);
  const valid = title.trim().length >= 5 && blurb.trim().length >= 10 && (!isPaid || Number(amount) > 0);
  const save = () => {
    if (busy || !valid) return;
    setBusy(true);
    onSave({ title: title.trim(), blurb: blurb.trim(), ...(isPaid ? { amount: Number(amount) } : {}), deadline: deadline || null, urgent });
  };
  return (
    <div onClick={onClose} style={modalOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ ...modalCard, maxWidth: 520 }}>
        <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 22, letterSpacing: "-0.02em", margin: 0, color: "var(--ink)" }}>Edit task</h2>
          <button onClick={onClose} style={closeBtn}>✕</button>
        </div>
        <div style={{ padding: "22px 26px", display: "flex", flexDirection: "column", gap: 18 }}>
          <Field label="Title"><input value={title} onChange={(e) => setTitle(e.target.value)} style={inputStyle} /></Field>
          <Field label="Description"><textarea value={blurb} onChange={(e) => setBlurb(e.target.value)} rows={3} style={{ ...inputStyle, resize: "vertical", lineHeight: 1.5 }} /></Field>
          {isPaid && (
            <Field label="Budget">
              <div style={{ position: "relative", display: "flex", alignItems: "center", maxWidth: 200 }}>
                <span style={{ position: "absolute", left: 15, fontWeight: 700, color: "var(--ink-2)", fontSize: 16 }}>{task.pay.cur}</span>
                <input value={amount} onChange={(e) => setAmount(e.target.value.replace(/[^\d]/g, ""))} inputMode="numeric" style={{ ...inputStyle, paddingLeft: 32, fontWeight: 700, fontSize: 17 }} />
              </div>
            </Field>
          )}
          <Field label="Deadline (optional)"><input type="datetime-local" value={deadline} min={nowLocal} onChange={(e) => setDeadline(e.target.value)} style={{ ...inputStyle, maxWidth: 280, cursor: "pointer" }} /></Field>
          <label style={{ display: "flex", alignItems: "center", gap: 11, cursor: "pointer" }}>
            <span onClick={() => setUrgent(!urgent)} style={{ width: 44, height: 26, borderRadius: 999, background: urgent ? "var(--clay)" : "var(--line-dk)", position: "relative", transition: "background .2s", flexShrink: 0 }}>
              <span style={{ position: "absolute", top: 3, left: urgent ? 21 : 3, width: 20, height: 20, borderRadius: "50%", background: "#fff", transition: "left .2s" }} />
            </span>
            <span style={{ fontSize: 15, fontWeight: 600, color: "var(--ink)" }}>Mark as urgent</span>
          </label>
        </div>
        <div style={{ padding: "18px 26px", borderTop: "1px solid var(--line)", display: "flex", gap: 10, justifyContent: "flex-end" }}>
          <Button variant="ghost" onClick={onClose} disabled={busy}>Cancel</Button>
          <Button icon="check" onClick={save} disabled={busy || !valid}>{busy ? "Saving…" : "Save changes"}</Button>
        </div>
      </div>
    </div>
  );
}

/* ===== CANCEL & REFUND MODAL (poster) ===== */
function CancelTaskModal({ status, workerName, isFavor, onClose, onConfirm }) {
  const [reason, setReason] = useS4("");
  const [busy, setBusy] = useS4(false);
  const hasWorker = status === "assigned" || status === "proof_submitted";
  const first = workerName ? workerName.split(" ")[0] : "the worker";
  const title = isFavor
    ? (status === "proof_submitted" ? "Reject & cancel?" : "Cancel this task?")
    : (status === "open" ? "Cancel this task?" : status === "proof_submitted" ? "Reject proof & refund?" : "Cancel & get a refund?");
  const body = isFavor
    ? (status === "proof_submitted" ? `You're rejecting ${first}'s work — the task will be cancelled.`
       : status === "open" ? "Your task will be removed from the board."
       : `The task will be cancelled. ${first} will be told it was called off.`)
    : (status === "open" ? "Your task will be removed and the payment you're holding comes straight back to you."
       : status === "proof_submitted" ? `You're rejecting ${first}'s proof. The task is cancelled and your payment is refunded.`
       : `The task will be cancelled and your payment refunded. ${first} will be told it was called off.`);
  const confirm = () => { if (busy) return; setBusy(true); onConfirm(reason.trim()); };
  return (
    <div onClick={onClose} style={modalOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ ...modalCard, maxWidth: 440 }}>
        <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 22, letterSpacing: "-0.02em", margin: 0, color: "var(--ink)" }}>{title}</h2>
          <button onClick={onClose} style={closeBtn}>✕</button>
        </div>
        <div style={{ padding: "22px 26px", display: "flex", flexDirection: "column", gap: 16 }}>
          <p style={{ margin: 0, fontSize: 15, color: "var(--ink-2)", lineHeight: 1.55 }}>{body}</p>
          {!isFavor && (
            <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "11px 13px", borderRadius: 10, background: "var(--green-3)", color: "var(--green)", fontSize: 13.5, fontWeight: 600 }}>
              <Icon name="shield" size={15} /> Refund returns to your original payment method.
            </div>
          )}
          {hasWorker && (
            <label style={{ display: "block" }}>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 }}>Reason <span style={{ fontWeight: 400, color: "var(--ink-2)" }}>(optional — shared with {first})</span></div>
              <textarea value={reason} onChange={(e) => setReason(e.target.value)} rows={2} placeholder="e.g. Plans changed / didn't receive the deliverable" style={{ ...inputStyle, resize: "vertical", lineHeight: 1.5 }} />
            </label>
          )}
        </div>
        <div style={{ padding: "18px 26px", borderTop: "1px solid var(--line)", display: "flex", gap: 10, justifyContent: "flex-end" }}>
          <Button variant="ghost" onClick={onClose} disabled={busy}>Keep task</Button>
          <Button icon="ban" style={{ background: "var(--clay)", color: "#fff" }} disabled={busy} onClick={confirm}>
            {busy ? "Cancelling…" : isFavor ? "Cancel task" : status === "proof_submitted" ? "Reject & refund" : "Cancel & refund"}
          </Button>
        </div>
      </div>
    </div>
  );
}

function StatusBadge({ status }) {
  const map = {
    open:            { label: "Open for applications", dot: "var(--blue)",    bg: "color-mix(in srgb, var(--blue) 12%, transparent)",   color: "var(--blue)"    },
    assigned:        { label: "In progress",            dot: "var(--amber)",   bg: "color-mix(in srgb, var(--amber) 18%, transparent)",  color: "var(--amber-dk)" },
    proof_submitted: { label: "Proof submitted",        dot: "var(--clay)",    bg: "color-mix(in srgb, var(--clay) 12%, transparent)",   color: "var(--clay)"    },
    completed:       { label: "Completed",              dot: "var(--green)",   bg: "var(--green-3)",                                      color: "var(--green)"   },
    cancelled:       { label: "Cancelled · refunded",   dot: "var(--ink-2)",   bg: "var(--ink-3)",                                        color: "var(--ink-2)"   },
  };
  const s = map[status] || map.open;
  return (
    <div style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 13, fontWeight: 700, color: s.color, background: s.bg, padding: "6px 13px", borderRadius: 999 }}>
      <span style={{ width: 7, height: 7, borderRadius: "50%", background: s.dot }} />
      {s.label}
    </div>
  );
}

function ApplicantRow({ app, cur, last, onAccept, onReject, onMessage }) {
  const p = PEOPLE[app.handle] || app.profile || { name: "Applicant", handle: "@user", city: "", verified: false, rating: 0, jobs: 0 };
  const [busy, setBusy] = useS4(false);
  return (
    <div style={{ paddingBottom: last ? 0 : 16, marginBottom: last ? 0 : 16, borderBottom: last ? "none" : "1px solid var(--line)" }}>
      <div style={{ display: "flex", gap: 10, alignItems: "flex-start", marginBottom: 10 }}>
        <Avatar name={p.name} size={38} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 5, marginBottom: 3 }}>
            <span style={{ fontWeight: 700, fontSize: 14.5, color: "var(--ink)" }}>{p.name}</span>
            {p.verified && <VerifiedTick size={13} />}
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: "var(--ink-2)", flexWrap: "wrap" }}>
            <Stars value={p.rating} size={12} />
            <span>· {p.jobs} tasks</span>
            {app.price && cur && (
              <span style={{ fontWeight: 700, color: "var(--ink)" }}>· {cur}{app.price.toLocaleString()}</span>
            )}
            <span style={{ color: "var(--ink-2)" }}>
              · {app.when === "asap" ? "ASAP" : app.when === "this-week" ? "This week" : app.when.charAt(0).toUpperCase() + app.when.slice(1)}
            </span>
          </div>
        </div>
      </div>
      <p style={{ fontSize: 13.5, color: "var(--ink)", lineHeight: 1.45, margin: "0 0 10px", background: "var(--ink-3)", borderRadius: 9, padding: "9px 12px" }}>
        "{app.msg}"
      </p>
      <div style={{ display: "flex", gap: 7, alignItems: "center" }}>
        <Button size="sm" icon="check" disabled={busy} onClick={() => { if (busy) return; setBusy(true); onAccept(); }}>{busy ? "Accepting…" : "Accept"}</Button>
        <Button size="sm" variant="ghost" icon="chat" onClick={onMessage}>Message</Button>
        <button onClick={onReject} style={{ marginLeft: "auto", background: "none", border: "none", cursor: "pointer", fontSize: 13, color: "var(--ink-2)", fontFamily: "var(--sans)", fontWeight: 600, padding: "4px 0" }}>
          Decline
        </button>
      </div>
    </div>
  );
}

/* ===== PROOF RELEASE MODAL (poster) ===== */
function ProofReleaseModal({ meta, isFavor, task, onClose, onConfirm }) {
  const alreadyHasProof = meta?.status === "proof_submitted" && meta?.proof;
  const [notes, setNotes] = useS4("");
  const [busy, setBusy] = useS4(false);

  const isPaid = !isFavor && task?.pay?.kind === "fixed";
  const amount = isPaid ? (task.pay.amount || 0) : 0;
  const cur = task?.pay?.cur || "₹";
  const commissionRate = window.PLATFORM_COMMISSION || 10;
  const commissionAmount = isPaid ? Math.round(amount * commissionRate) / 100 : 0;
  const workerGets = isPaid ? amount - commissionAmount : 0;

  const confirm = () => { if (busy) return; setBusy(true); onConfirm(alreadyHasProof ? meta.proof : notes.trim()); };
  return (
    <div onClick={onClose} style={modalOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ ...modalCard, maxWidth: 460 }}>
        <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 22, letterSpacing: "-0.02em", margin: 0, color: "var(--ink)" }}>{isFavor ? "Confirm completion" : "Release payment"}</h2>
          <button onClick={onClose} style={closeBtn}>✕</button>
        </div>
        <div style={{ padding: "22px 26px", display: "flex", flexDirection: "column", gap: 16 }}>
          <p style={{ margin: 0, fontSize: 15.5, color: "var(--ink-2)", lineHeight: 1.5 }}>
            {isFavor ? "This marks the task complete and lets you leave a review. This can't be undone." : "Once released, funds are sent to the worker's UPI and the task is marked complete. This can't be undone."}
          </p>

          {/* Payment breakdown for paid tasks */}
          {isPaid && amount > 0 && (
            <div style={{ background: "var(--ink-3)", borderRadius: 14, padding: "16px 18px" }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14.5, color: "var(--ink)", marginBottom: 8 }}>
                <span>Task budget</span>
                <span style={{ fontWeight: 700 }}>{cur}{amount.toLocaleString()}</span>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5, color: "var(--ink-2)", marginBottom: 8 }}>
                <span>Platform fee ({commissionRate}%)</span>
                <span>−{cur}{commissionAmount.toLocaleString()}</span>
              </div>
              <div style={{ height: 1, background: "var(--line)", margin: "4px 0 8px" }} />
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 15, color: "var(--green)", fontWeight: 700 }}>
                <span>Worker receives</span>
                <span>{cur}{workerGets.toLocaleString()}</span>
              </div>
            </div>
          )}

          {alreadyHasProof ? (
            <div>
              <div style={{ fontSize: 12, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-2)", marginBottom: 8 }}>Submitted proof</div>
              <ProofGallery photos={meta.proofPhotos} />
              {meta.proof && (
                <div style={{ background: "var(--ink-3)", borderRadius: 12, padding: "12px 14px", fontSize: 14, color: "var(--ink)", lineHeight: 1.5 }}>
                  "{meta.proof}"
                </div>
              )}
            </div>
          ) : (
            <Field label="What did they deliver? (optional)" hint="A note for your records — photos, links, summary…">
              <textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={3}
                placeholder="Sent 4 photos of the display + a voice note with the price details…"
                style={{ ...inputStyle, resize: "vertical", lineHeight: 1.5 }} />
            </Field>
          )}
        </div>
        <div style={{ padding: "18px 26px", borderTop: "1px solid var(--line)", display: "flex", gap: 10, justifyContent: "flex-end" }}>
          <Button variant="ghost" onClick={onClose} disabled={busy}>Cancel</Button>
          <Button icon={isFavor ? "check" : "wallet"} disabled={busy} onClick={confirm}>
            {busy ? (isFavor ? "Completing…" : "Releasing payment…") : isFavor ? "Confirm & complete" : `Release ${cur}${workerGets.toLocaleString()}`}
          </Button>
        </div>
      </div>
    </div>
  );
}

/* ===== REVIEW MODAL ===== */
function ReviewModal({ targetName, onClose, onSubmit }) {
  const [stars, setStars] = useS4(5);
  const [text, setText] = useS4("");
  const firstName = targetName.split(" ")[0];
  return (
    <div onClick={onClose} style={modalOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ ...modalCard, maxWidth: 440 }}>
        <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 22, letterSpacing: "-0.02em", margin: 0, color: "var(--ink)" }}>
            Rate {firstName}
          </h2>
          <button onClick={onClose} style={closeBtn}>✕</button>
        </div>
        <div style={{ padding: "22px 26px", display: "flex", flexDirection: "column", gap: 20 }}>
          <div>
            <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--ink)", marginBottom: 12 }}>How did it go?</div>
            <div style={{ display: "flex", gap: 4 }}>
              {[1, 2, 3, 4, 5].map((s) => (
                <button key={s} onClick={() => setStars(s)} style={{ background: "none", border: "none", cursor: "pointer", padding: 4, color: s <= stars ? "var(--amber)" : "var(--line-dk)", transition: "color .1s" }}>
                  <Icon name="star" size={34} fill={s <= stars} stroke={s <= stars ? 0 : 1.5} />
                </button>
              ))}
            </div>
          </div>
          <Field label={`Leave a note for ${firstName} (optional)`}>
            <textarea value={text} onChange={(e) => setText(e.target.value)} rows={3}
              placeholder="Fast, reliable, exactly what I asked for…"
              style={{ ...inputStyle, resize: "vertical", lineHeight: 1.5 }} />
          </Field>
        </div>
        <div style={{ padding: "18px 26px", borderTop: "1px solid var(--line)", display: "flex", gap: 10, justifyContent: "flex-end" }}>
          <Button variant="ghost" onClick={onClose}>Skip</Button>
          <Button icon="star" onClick={() => onSubmit({ stars, text: text.trim() })}>Submit review</Button>
        </div>
      </div>
    </div>
  );
}

/* ===== PROOF SUBMIT MODAL (worker) ===== */
function ProofSubmitModal({ task, onClose, onSubmit }) {
  const [proof, setProof] = useS4("");
  const [photos, setPhotos] = useS4([]); // [{ url, file }]
  const [err, setErr] = useS4("");
  const [busy, setBusy] = useS4(false);

  const addPhotos = (e) => {
    const files = Array.from(e.target.files || []);
    const next = files.slice(0, 6 - photos.length).map((file) => ({ url: URL.createObjectURL(file), file }));
    setPhotos((p) => [...p, ...next]);
    setErr("");
  };
  const removePhoto = (i) => setPhotos((p) => p.filter((_, idx) => idx !== i));

  const submit = async () => {
    if (photos.length === 0 && proof.trim().length < 10) {
      setErr("Add at least one photo, or describe what you delivered.");
      return;
    }
    setBusy(true);
    await onSubmit({ text: proof.trim(), photos });
  };

  return (
    <div onClick={onClose} style={modalOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ ...modalCard, maxWidth: 500 }}>
        <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 14 }}>
          <div>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--clay)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Submit proof</div>
            <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 21, letterSpacing: "-0.02em", margin: "6px 0 0", color: "var(--ink)", lineHeight: 1.15 }}>
              {task.title}
            </h2>
          </div>
          <button onClick={onClose} style={closeBtn}>✕</button>
        </div>
        <div style={{ padding: "22px 26px", display: "flex", flexDirection: "column", gap: 18 }}>
          {task.proof && (
            <div style={{ background: "var(--ink-3)", borderRadius: 10, padding: "10px 14px", fontSize: 13.5 }}>
              <span style={{ fontWeight: 700, color: "var(--ink)" }}>Required: </span>
              <span style={{ color: "var(--ink-2)" }}>{task.proof}</span>
            </div>
          )}

          {/* photo uploader */}
          <div>
            <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--ink)", marginBottom: 3 }}>Photos</div>
            <div style={{ fontSize: 13, color: "var(--ink-2)", marginBottom: 9 }}>The proof of your work — up to 6 photos.</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(84px, 1fr))", gap: 8 }}>
              {photos.map((ph, i) => (
                <div key={i} style={{ position: "relative", aspectRatio: "1", borderRadius: 10, overflow: "hidden", border: "1px solid var(--line)" }}>
                  <img src={ph.url} alt={`proof ${i + 1}`} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                  <button onClick={() => removePhoto(i)} style={{ position: "absolute", top: 4, right: 4, width: 22, height: 22, borderRadius: "50%", background: "rgba(20,14,6,.7)", color: "#fff", border: "none", cursor: "pointer", fontSize: 12, display: "grid", placeItems: "center" }}>✕</button>
                </div>
              ))}
              {photos.length < 6 && (
                <label style={{ aspectRatio: "1", borderRadius: 10, border: "2px dashed var(--line-dk)", background: "var(--ink-3)", display: "grid", placeItems: "center", cursor: "pointer", color: "var(--ink-2)" }}>
                  <div style={{ textAlign: "center" }}>
                    <Icon name="camera" size={22} stroke={1.7} />
                    <div style={{ fontSize: 11, fontWeight: 600, marginTop: 3 }}>Add</div>
                  </div>
                  <input type="file" accept="image/*" multiple capture="environment" onChange={addPhotos} style={{ display: "none" }} />
                </label>
              )}
            </div>
          </div>

          <Field label="Notes (optional)" hint="Summary, links, anything the poster should know.">
            <textarea value={proof} onChange={(e) => { setProof(e.target.value); setErr(""); }} rows={3}
              placeholder="256GB is ₹89,900 and 512GB is ₹1,09,900. Both in stock. Photos of the display + price cards attached."
              style={{ ...inputStyle, resize: "vertical", lineHeight: 1.5 }} />
          </Field>
          {err && (
            <div style={{ color: "var(--clay)", fontSize: 14, fontWeight: 600, display: "flex", gap: 7, alignItems: "center" }}>
              <Icon name="bolt" size={15} /> {err}
            </div>
          )}
        </div>
        <div style={{ padding: "18px 26px", borderTop: "1px solid var(--line)", display: "flex", gap: 10, justifyContent: "flex-end" }}>
          <Button variant="ghost" onClick={onClose} disabled={busy}>Cancel</Button>
          <Button icon="check" onClick={submit} disabled={busy}>{busy ? "Submitting…" : "Submit proof"}</Button>
        </div>
      </div>
    </div>
  );
}

/* ===== PROOF GALLERY (poster sees submitted photos) ===== */
function ProofGallery({ photos }) {
  if (!photos || photos.length === 0) return null;
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(72px, 1fr))", gap: 6, marginBottom: 14 }}>
      {photos.map((url, i) => (
        <a key={i} href={url} target="_blank" rel="noreferrer" style={{ display: "block", aspectRatio: "1", borderRadius: 9, overflow: "hidden", border: "1px solid var(--line)" }}>
          <img src={url} alt={`proof ${i + 1}`} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
        </a>
      ))}
    </div>
  );
}

/* ===== MESSAGE MODAL ===== */
function MsgTicks({ status }) {
  const two = status === "delivered" || status === "seen";
  const color = status === "seen" ? "#7FB3FF" : "rgba(255,255,255,.65)";
  return (
    <span style={{ display: "inline-flex", alignItems: "center", marginLeft: 5, color }}>
      <Icon name="check" size={12} stroke={2.6} />
      {two && <Icon name="check" size={12} stroke={2.6} style={{ marginLeft: -6 }} />}
    </span>
  );
}

function MessageModal({ theirHandle, theirProfile, messages, onSend, onClose }) {
  const [txt, setTxt] = useS4("");
  const [photo, setPhoto] = useS4(null); // { url, file }
  const p = theirProfile || PEOPLE[theirHandle] || { name: "User", city: "" };
  const send = () => {
    if (!txt.trim() && !photo) return;
    onSend({ text: txt.trim(), photo });
    setTxt(""); setPhoto(null);
  };
  const pickPhoto = (e) => { const f = e.target.files[0]; if (!f) return; setPhoto({ url: URL.createObjectURL(f), file: f }); };
  const endRef = React.useRef(null);
  React.useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messages]);

  return (
    <div onClick={onClose} style={modalOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ ...modalCard, maxWidth: 460, display: "flex", flexDirection: "column", maxHeight: "82vh" }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 12, flexShrink: 0 }}>
          <Avatar name={p.name} size={40} />
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 15.5, color: "var(--ink)" }}>{p.name}</div>
            {p.city && <div style={{ fontSize: 12.5, color: "var(--ink-2)" }}>{p.city}</div>}
          </div>
          <button onClick={onClose} style={closeBtn}>✕</button>
        </div>

        <div style={{ flex: 1, overflowY: "auto", padding: "16px 20px", display: "flex", flexDirection: "column", gap: 10, minHeight: 220, background: "var(--paper)" }}>
          {messages.length === 0 && (
            <div style={{ textAlign: "center", color: "var(--ink-2)", fontSize: 14, padding: "48px 20px", lineHeight: 1.5 }}>
              Start the conversation — ask a question or confirm the details before committing.
            </div>
          )}
          {messages.map((m, i) => {
            const mine = m.from === "me";
            return (
              <div key={i} style={{ display: "flex", justifyContent: mine ? "flex-end" : "flex-start" }}>
                <div style={{
                  maxWidth: "78%",
                  background: mine ? "var(--clay)" : "var(--surface)",
                  border: mine ? "none" : "1px solid var(--line)",
                  color: mine ? "#fff" : "var(--ink)",
                  borderRadius: mine ? "16px 16px 4px 16px" : "16px 16px 16px 4px",
                  padding: m.photo ? 4 : "10px 14px", fontSize: 14.5, lineHeight: 1.4, overflow: "hidden",
                }}>
                  {m.photo && (
                    <a href={m.photo} target="_blank" rel="noreferrer" style={{ display: "block" }}>
                      <img src={m.photo} alt="shared" style={{ maxWidth: "100%", maxHeight: 220, borderRadius: 12, display: "block", objectFit: "cover" }} />
                    </a>
                  )}
                  {m.text && <div style={{ padding: m.photo ? "8px 10px 4px" : 0 }}>{m.text}</div>}
                  {mine && (
                    <div style={{ display: "flex", justifyContent: "flex-end", alignItems: "center", fontSize: 10.5, opacity: 0.85, padding: m.photo ? "0 10px 6px" : "3px 0 0" }}>
                      {m.status === "seen" ? "Seen" : m.status === "delivered" ? "Delivered" : "Sent"}
                      <MsgTicks status={m.status || "sent"} />
                    </div>
                  )}
                </div>
              </div>
            );
          })}
          <div ref={endRef} />
        </div>

        {/* photo preview before sending */}
        {photo && (
          <div style={{ padding: "10px 20px 0", flexShrink: 0 }}>
            <div style={{ position: "relative", display: "inline-block" }}>
              <img src={photo.url} alt="to send" style={{ height: 64, borderRadius: 10, border: "1px solid var(--line)" }} />
              <button onClick={() => setPhoto(null)} style={{ position: "absolute", top: -7, right: -7, width: 22, height: 22, borderRadius: "50%", background: "var(--ink)", color: "#fff", border: "none", cursor: "pointer", fontSize: 12 }}>✕</button>
            </div>
          </div>
        )}

        <div style={{ padding: "12px 20px", borderTop: "1px solid var(--line)", display: "flex", gap: 8, flexShrink: 0, alignItems: "center" }}>
          <label style={{ cursor: "pointer", color: "var(--ink-2)", display: "grid", placeItems: "center", flexShrink: 0, padding: 4 }}>
            <Icon name="image" size={22} stroke={1.8} />
            <input type="file" accept="image/*" onChange={pickPhoto} style={{ display: "none" }} />
          </label>
          <input value={txt} onChange={(e) => setTxt(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
            placeholder={`Message ${p.name.split(" ")[0]}…`}
            style={{ ...inputStyle, flex: 1, padding: "11px 14px" }} />
          <Button icon="arrow" onClick={send} disabled={!txt.trim() && !photo}>Send</Button>
        </div>
      </div>
    </div>
  );
}

/* ===== INBOX PAGE ===== */
function InboxPage({ go, messages, openMessage, authUser, demoMode }) {
  const [threads, setThreads] = useS4(null); // null = loading

  React.useEffect(() => {
    if (demoMode) {
      // build from local messages state (handle -> msg array)
      const t = Object.entries(messages || {}).map(([handle, msgs]) => {
        const p = PEOPLE[handle] || { name: "User", city: "" };
        const last = msgs[msgs.length - 1];
        return {
          id: handle,
          profile: { name: p.name, city: p.city, handle: p.handle, verified: p.verified },
          lastMessage: last?.text || (last?.photo ? "📷 Photo" : ""),
          lastTime: last?.time || null,
          unread: msgs.filter(m => m.from === "them").length,
        };
      });
      setThreads(t);
    } else if (authUser) {
      Messages.inbox(authUser.id).then(({ threads: t }) => setThreads(t || []));
    } else {
      setThreads([]);
    }
  }, [demoMode, authUser]);

  return (
    <Wrap style={{ paddingTop: 32, paddingBottom: 60, maxWidth: 600 }}>
      <button onClick={() => go("dashboard")} 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
      </button>

      <h1 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(26px,3.5vw,38px)", letterSpacing: "-0.03em", margin: "0 0 28px", color: "var(--ink)" }}>Messages</h1>

      {threads === null ? (
        <div style={{ color: "var(--ink-2)", fontSize: 15 }}>Loading…</div>
      ) : threads.length === 0 ? (
        <div style={{ textAlign: "center", padding: "64px 20px" }}>
          <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--ink-3)", display: "grid", placeItems: "center", margin: "0 auto 18px", color: "var(--ink-2)" }}>
            <Icon name="chat" size={28} stroke={1.6} />
          </div>
          <div style={{ fontSize: 17, fontWeight: 700, color: "var(--ink)", marginBottom: 6 }}>No messages yet</div>
          <div style={{ fontSize: 14.5, color: "var(--ink-2)", lineHeight: 1.55 }}>When you apply to a task or accept a worker,<br />you can chat with them here.</div>
          <div style={{ marginTop: 22 }}>
            <Button icon="search" onClick={() => go("browse")}>Browse tasks</Button>
          </div>
        </div>
      ) : threads.map(thread => (
        <button key={thread.id} onClick={() => openMessage(thread.id)} style={{
          width: "100%", display: "flex", alignItems: "center", gap: 14,
          padding: "14px 16px", background: "var(--surface)", border: "1px solid var(--line)",
          borderRadius: 16, marginBottom: 10, cursor: "pointer", textAlign: "left",
          transition: "border-color .15s, box-shadow .15s",
        }}
          onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--line-dk)"; e.currentTarget.style.boxShadow = "0 4px 16px -10px rgba(40,30,15,.2)"; }}
          onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--line)"; e.currentTarget.style.boxShadow = "none"; }}
        >
          <div style={{ position: "relative", flexShrink: 0 }}>
            <Avatar name={thread.profile?.name || "User"} size={48} />
            {thread.unread > 0 && (
              <span style={{ position: "absolute", top: -3, right: -3, width: 18, height: 18, borderRadius: "50%", background: "var(--clay)", color: "#fff", fontSize: 10, fontWeight: 700, display: "grid", placeItems: "center", border: "2px solid var(--surface)" }}>
                {thread.unread > 9 ? "9+" : thread.unread}
              </span>
            )}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
              <span style={{ fontWeight: 700, fontSize: 15, color: "var(--ink)", display: "flex", alignItems: "center", gap: 5 }}>
                {thread.profile?.name || "User"}
                {thread.profile?.verified && <VerifiedTick size={13} />}
              </span>
              {thread.lastTime && (
                <span style={{ fontSize: 12, color: "var(--ink-2)" }}>{timeAgo(thread.lastTime)}</span>
              )}
            </div>
            <div style={{ fontSize: 13.5, color: thread.unread > 0 ? "var(--ink)" : "var(--ink-2)", fontWeight: thread.unread > 0 ? 600 : 400, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
              {thread.lastMessage || "Start a conversation"}
            </div>
          </div>
        </button>
      ))}
    </Wrap>
  );
}

/* ===== BUDGET BOOST MODAL ===== */
function BudgetBoostModal({ task, onClose, onConfirm }) {
  const cur = task.pay.cur;
  const currentAmount = task.pay.amount;
  const [newAmount, setNewAmount] = useS4(String(Math.round(currentAmount * 1.3)));
  const parsed = Number(newAmount) || 0;
  const diff = parsed - currentAmount;
  const valid = parsed > currentAmount;

  return (
    <div onClick={onClose} style={modalOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ ...modalCard, maxWidth: 440 }}>
        <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 22, letterSpacing: "-0.02em", margin: 0, color: "var(--ink)" }}>Boost budget</h2>
          <button onClick={onClose} style={closeBtn}>✕</button>
        </div>
        <div style={{ padding: "22px 26px", display: "flex", flexDirection: "column", gap: 18 }}>
          <p style={{ margin: 0, fontSize: 15, color: "var(--ink-2)", lineHeight: 1.5 }}>
            Increase your budget to attract more applicants. The extra amount will be held securely.
          </p>

          <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
            <div style={{ textAlign: "center" }}>
              <div style={{ fontSize: 12, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-2)", marginBottom: 6 }}>Current</div>
              <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 26, color: "var(--ink-2)", textDecoration: "line-through", letterSpacing: "-0.02em" }}>{cur}{currentAmount.toLocaleString()}</div>
            </div>
            <Icon name="arrow" size={22} style={{ color: "var(--ink-2)", marginTop: 18 }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--ink-2)", marginBottom: 6 }}>New amount</div>
              <div style={{ position: "relative", display: "flex", alignItems: "center" }}>
                <span style={{ position: "absolute", left: 14, fontWeight: 700, color: "var(--ink-2)", fontSize: 18 }}>{cur}</span>
                <input value={newAmount} onChange={(e) => setNewAmount(e.target.value.replace(/[^\d]/g, ""))} inputMode="numeric"
                  style={{ ...inputStyle, paddingLeft: 32, fontWeight: 700, fontSize: 22, fontFamily: "var(--display)", letterSpacing: "-0.02em" }} />
              </div>
            </div>
          </div>

          {valid && (
            <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 14px", borderRadius: 12, background: "color-mix(in srgb, var(--green) 10%, transparent)", color: "var(--green)", fontSize: 14, fontWeight: 600 }}>
              <Icon name="wallet" size={17} />
              <span>Extra {cur}{diff.toLocaleString()} will be added to escrow</span>
            </div>
          )}
          {!valid && parsed > 0 && (
            <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--clay)", fontSize: 13.5, fontWeight: 600 }}>
              <Icon name="bolt" size={15} /> New amount must be higher than {cur}{currentAmount.toLocaleString()}
            </div>
          )}
        </div>
        <div style={{ padding: "18px 26px", borderTop: "1px solid var(--line)", display: "flex", gap: 10, justifyContent: "flex-end" }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button icon="bolt" disabled={!valid} onClick={() => onConfirm(parsed)}>Boost to {cur}{parsed.toLocaleString()}</Button>
        </div>
      </div>
    </div>
  );
}

function ReportModal({ person, onClose, onSubmit }) {
  const [reason, setReason] = useW1("");

  return (
    <div onClick={onClose} style={modalOverlay}>
      <div onClick={e => e.stopPropagation()} style={{ ...modalCard, maxWidth: 440 }}>
        <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 22, letterSpacing: "-0.02em", margin: 0, color: "var(--clay)" }}>Report {person?.name || "Doer"}</h2>
          <button onClick={onClose} style={closeBtn}>✕</button>
        </div>
        <div style={{ padding: "22px 26px" }}>
          <p style={{ margin: "0 0 16px", fontSize: 14.5, color: "var(--ink-2)", lineHeight: 1.5 }}>
            Are you sure you want to issue a strike to this user? This will be reviewed by the admin. 3 strikes result in a permanent ban.
          </p>
          <textarea
            autoFocus
            value={reason} onChange={e => setReason(e.target.value)}
            placeholder={`Why are you reporting ${person?.name || "them"}?`}
            style={{ width: "100%", height: 100, padding: 14, borderRadius: 12, border: "1px solid var(--line)", background: "var(--surface)", fontFamily: "inherit", fontSize: 15, color: "var(--ink)", resize: "none", boxSizing: "border-box" }}
          />
          <div style={{ display: "flex", gap: 10, marginTop: 20 }}>
            <Button full size="md" variant="ghost" onClick={onClose}>Cancel</Button>
            <Button full size="md" variant="dark" icon="ban" style={{ background: "var(--clay)", borderColor: "var(--clay)" }} onClick={() => onSubmit(reason)} disabled={!reason.trim()}>Submit Report</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ManageTask, StatusBadge, ApplicantRow, ProofReleaseModal, ReviewModal, ProofSubmitModal, ProofGallery, MessageModal, InboxPage, BudgetBoostModal, CancelTaskModal, EditTaskModal, ReportModal });
