// screens-profile.jsx — Profile, Settings, Logout
const { useState: useP1 } = React;

function ProfilePage({ go, onLogout, verificationStatus, rejectReason, user, email, onSave }) {
  const u = user || ME;
  const [editing, setEditing] = useP1(false);
  const [profile, setProfile] = useP1({
    name: u.name || "You", phone: u.phone || "", bio: u.bio || "", city: u.city || "Hyderabad",
    skills: u.skills || [], availabilityDays: u.availabilityDays || [], availabilityHours: u.availabilityHours || "",
    travelRadius: u.travelRadius || "", vehicle: u.vehicle || "", avatarUrl: u.avatarUrl || null,
  });
  const [showLogoutConfirm, setShowLogoutConfirm] = useP1(false);

  const vStatus = verificationStatus || "unverified"; // unverified | pending | verified
  const vColors = ({ unverified: { bg: "color-mix(in srgb, var(--clay) 12%, transparent)", color: "var(--clay)", label: "Not verified" }, pending: { bg: "color-mix(in srgb, var(--amber) 16%, transparent)", color: "var(--amber-dk)", label: "Pending review" }, verified: { bg: "var(--green-3)", color: "var(--green)", label: "Verified" }, rejected: { bg: "color-mix(in srgb, var(--clay) 12%, transparent)", color: "var(--clay)", label: "Rejected" } })[vStatus] || { bg: "var(--ink-3)", color: "var(--ink-2)", label: "Unknown" };

  return (
    <Wrap style={{ paddingTop: 36, paddingBottom: 40 }}>
      <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: 16 }}>
        <Icon name="back" size={17} /> Back
      </button>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 340px", gap: 32, alignItems: "start" }}>
        {/* Left column */}
        <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
          {/* Profile header card */}
          <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 20, padding: 28 }}>
            <div style={{ display: "flex", gap: 18, alignItems: "flex-start" }}>
              <Avatar name={profile.name === "You" ? "You Me" : profile.name} size={72} ring src={profile.avatarUrl} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                  <h1 style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 28, letterSpacing: "-0.03em", margin: 0, color: "var(--ink)" }}>{profile.name}</h1>
                  {vStatus === "verified" && <VerifiedTick size={20} />}
                  <span style={{ fontSize: 12.5, fontWeight: 700, padding: "4px 11px", borderRadius: 999, background: vColors.bg, color: vColors.color }}>{vColors.label}</span>
                </div>
                <div style={{ fontSize: 15, color: "var(--ink-2)", marginTop: 4 }}>{email || u.handle || ME.handle}</div>
                <div style={{ display: "flex", gap: 20, marginTop: 12, fontSize: 14, color: "var(--ink-2)" }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="pin" size={15} /> {profile.city}</span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Stars value={u.rating ?? ME.rating} size={14} /></span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="check" size={15} /> {u.jobs ?? ME.jobs} tasks done</span>
                </div>
              </div>
              <Button variant="ghost" size="sm" icon="edit" onClick={() => setEditing(true)}>Edit</Button>
            </div>
            {profile.bio && <p style={{ fontSize: 15.5, lineHeight: 1.55, color: "var(--ink)", margin: "18px 0 0", padding: "16px 0 0", borderTop: "1px solid var(--line)" }}>{profile.bio}</p>}
          </div>

          {/* Skills / availability / travel */}
          {(profile.skills?.length > 0 || profile.availabilityDays?.length > 0 || profile.availabilityHours || profile.travelRadius || profile.vehicle) && (
            <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 20, padding: "8px 28px 28px" }}>
              <ProfileDetails profile={profile} />
            </div>
          )}

          {/* Verification CTA */}
          {vStatus !== "verified" && (
            <div onClick={() => go("verify")} style={{ background: "color-mix(in srgb, var(--clay) 6%, var(--surface))", border: "1px solid color-mix(in srgb, var(--clay) 24%, transparent)", borderRadius: 18, padding: 22, cursor: "pointer", display: "flex", gap: 16, alignItems: "flex-start" }}>
              <span style={{ width: 48, height: 48, borderRadius: 14, background: "color-mix(in srgb, var(--clay) 14%, transparent)", color: "var(--clay)", display: "grid", placeItems: "center", flexShrink: 0 }}>
                <Icon name={vStatus === "rejected" ? "bolt" : "shield"} size={24} />
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 18, color: "var(--ink)", letterSpacing: "-0.02em" }}>
                  {vStatus === "pending" ? "Verification in progress" : vStatus === "rejected" ? "Verification was rejected" : "Verify your identity"}
                </div>
                <div style={{ fontSize: 14, color: "var(--ink-2)", marginTop: 3 }}>
                  {vStatus === "pending" ? "We're reviewing your documents — usually takes 24h."
                    : vStatus === "rejected" ? "Fix the issue below and re-submit to get verified."
                    : "Get verified to unlock more tasks and build trust."}
                </div>
                {vStatus === "rejected" && rejectReason && (
                  <div style={{ marginTop: 12, background: "color-mix(in srgb, var(--clay) 8%, transparent)", border: "1px solid color-mix(in srgb, var(--clay) 22%, transparent)", borderRadius: 12, padding: "11px 13px", fontSize: 13.5, color: "var(--ink)", lineHeight: 1.5 }}>
                    <strong style={{ color: "var(--clay)" }}>Why it was rejected:</strong> {rejectReason}
                  </div>
                )}
                {vStatus === "rejected" && (
                  <div style={{ marginTop: 12 }}><Button size="sm" icon="shield" onClick={(e) => { e.stopPropagation(); go("verify"); }}>Re-submit verification</Button></div>
                )}
              </div>
              {vStatus !== "rejected" && <Icon name="arrow" size={20} style={{ color: "var(--clay)" }} />}
            </div>
          )}
        </div>

        {/* Right sidebar */}
        <div style={{ position: "sticky", top: 84, display: "flex", flexDirection: "column", gap: 16 }}>
          {/* Settings card */}
          <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 18, padding: 24 }}>
            <h3 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 20, letterSpacing: "-0.02em", margin: "0 0 18px", color: "var(--ink)" }}>Settings</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              {[
                { icon: "shield", label: "Verification", sub: vColors.label, action: () => go("verify") },
                { icon: "settings", label: "Notifications", sub: "Email & push" },
                { icon: "eye", label: "Privacy", sub: "Profile visibility" },
                { icon: "doc", label: "Terms & policies" },
              ].map((item) => (
                <button key={item.label} onClick={item.action} style={{ display: "flex", alignItems: "center", gap: 12, padding: "13px 12px", borderRadius: 10, border: "none", background: "transparent", cursor: "pointer", width: "100%", textAlign: "left", fontFamily: "var(--sans)" }}>
                  <span style={{ color: "var(--ink-2)" }}><Icon name={item.icon} size={19} /></span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 14.5, color: "var(--ink)" }}>{item.label}</div>
                    {item.sub && <div style={{ fontSize: 12.5, color: "var(--ink-2)" }}>{item.sub}</div>}
                  </div>
                  <Icon name="arrow" size={16} style={{ color: "var(--ink-2)" }} />
                </button>
              ))}
            </div>
          </div>

          {/* Danger zone */}
          <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 18, padding: 20 }}>
            <button onClick={() => setShowLogoutConfirm(true)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 14px", borderRadius: 10, border: "none", background: "color-mix(in srgb, var(--clay) 8%, transparent)", cursor: "pointer", width: "100%", textAlign: "left", fontFamily: "var(--sans)", color: "var(--clay)", fontWeight: 600, fontSize: 15 }}>
              <Icon name="logout" size={19} /> Log out
            </button>
          </div>
        </div>
      </div>

      {/* Edit modal */}
      {editing && <EditProfileModal profile={profile} onSave={(p) => { setProfile(p); onSave && onSave({ name: p.name, city: p.city, phone: p.phone, bio: p.bio, skills: p.skills, availabilityDays: p.availabilityDays, availabilityHours: p.availabilityHours, travelRadius: p.travelRadius, vehicle: p.vehicle, photoFile: p.photoFile, photoPreview: p.avatarUrl }); setEditing(false); }} onClose={() => setEditing(false)} />}

      {/* Logout confirm */}
      {showLogoutConfirm && (
        <div onClick={() => setShowLogoutConfirm(false)} style={modalOverlay}>
          <div onClick={(e) => e.stopPropagation()} style={{ ...modalCard, maxWidth: 400, padding: 28, textAlign: "center" }}>
            <div style={{ width: 56, height: 56, borderRadius: "50%", background: "color-mix(in srgb, var(--clay) 12%, transparent)", color: "var(--clay)", display: "grid", placeItems: "center", margin: "0 auto 18px" }}>
              <Icon name="logout" size={26} />
            </div>
            <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 22, margin: "0 0 8px", color: "var(--ink)" }}>Log out?</h2>
            <p style={{ fontSize: 15, color: "var(--ink-2)", margin: "0 0 24px" }}>You'll need to sign in again to access your tasks.</p>
            <div style={{ display: "flex", gap: 10, justifyContent: "center" }}>
              <Button variant="ghost" onClick={() => setShowLogoutConfirm(false)}>Cancel</Button>
              <Button style={{ background: "var(--clay)", color: "#fff" }} onClick={() => { setShowLogoutConfirm(false); go("home"); }}>Log out</Button>
            </div>
          </div>
        </div>
      )}
    </Wrap>
  );
}

function EditProfileModal({ profile, onSave, onClose }) {
  const [d, setD] = useP1({ ...profile, skills: profile.skills || [], availabilityDays: profile.availabilityDays || [], photoFile: null });
  const [skillInput, setSkillInput] = useP1("");
  const [error, setError] = useP1("");
  const set = (k, v) => setD((s) => ({ ...s, [k]: v }));
  const toggleDay = (v) => setD((s) => ({ ...s, availabilityDays: s.availabilityDays.includes(v) ? s.availabilityDays.filter((x) => x !== v) : [...s.availabilityDays, v] }));
  const addSkill = (s) => { const v = (s ?? skillInput).trim(); if (v && !d.skills.includes(v)) set("skills", [...d.skills, v]); setSkillInput(""); };
  const removeSkill = (s) => set("skills", d.skills.filter((x) => x !== s));
  const pickPhoto = (e) => { const f = e.target.files[0]; if (!f) return; set("photoFile", f); set("avatarUrl", URL.createObjectURL(f)); };

  const Chip = ({ active, onClick, children }) => (
    <button onClick={onClick} style={{ padding: "8px 14px", borderRadius: 999, cursor: "pointer", fontFamily: "var(--sans)", fontSize: 13.5, fontWeight: 600, border: "1.5px solid " + (active ? "var(--clay)" : "var(--line)"), background: active ? "color-mix(in srgb, var(--clay) 8%, var(--surface))" : "var(--surface)", color: active ? "var(--ink)" : "var(--ink-2)" }}>{children}</button>
  );
  const lbl = { fontSize: 13.5, fontWeight: 700, color: "var(--ink)", marginBottom: 8 };

  return (
    <div onClick={onClose} style={modalOverlay}>
      <div onClick={(e) => e.stopPropagation()} style={{ ...modalCard, maxWidth: 540 }}>
        <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center", position: "sticky", top: 0, background: "var(--surface)", zIndex: 1 }}>
          <h2 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 22, margin: 0, color: "var(--ink)" }}>Edit profile</h2>
          <button onClick={onClose} style={closeBtn}>✕</button>
        </div>
        <div style={{ padding: "22px 26px", display: "flex", flexDirection: "column", gap: 18 }}>
          <div style={{ display: "flex", justifyContent: "center" }}>
            <label style={{ position: "relative", cursor: "pointer" }}>
              <Avatar name={d.name === "You" ? "You Me" : d.name} size={80} src={d.avatarUrl} />
              <span style={{ position: "absolute", bottom: -2, right: -2, width: 30, height: 30, borderRadius: "50%", background: "var(--clay)", color: "#fff", border: "2px solid var(--surface)", display: "grid", placeItems: "center" }}>
                <Icon name="camera" size={14} stroke={2} />
              </span>
              <input type="file" accept="image/*" onChange={pickPhoto} style={{ display: "none" }} />
            </label>
          </div>
          <Field label="Display name"><input value={d.name} onChange={(e) => { set("name", e.target.value.slice(0, 50)); setError(""); }} maxLength={50} style={inputStyle} /></Field>
          <Field label="Phone number">
            <input type="tel" value={d.phone || ""} onChange={(e) => { const digits = e.target.value.replace(/\D/g, "").slice(0, 10); set("phone", digits); setError(""); }} placeholder="9876543210" inputMode="numeric" maxLength={10} style={inputStyle} />
            <div style={{ fontSize: 12.5, color: (d.phone || "").length > 0 && (d.phone || "").length < 10 ? "var(--clay)" : "var(--ink-2)", marginTop: 6 }}>{(d.phone || "").length > 0 ? `${(d.phone || "").length}/10 digits` : "10-digit mobile number (without +91)"}</div>
          </Field>
          <Field label="City"><input value={d.city} onChange={(e) => { set("city", e.target.value.slice(0, 50)); setError(""); }} maxLength={50} style={inputStyle} /></Field>
          <Field label="Bio"><textarea value={d.bio} onChange={(e) => set("bio", e.target.value)} rows={3} maxLength={240} style={{ ...inputStyle, resize: "vertical", lineHeight: 1.5 }} /></Field>

          {/* skills */}
          <div>
            <div style={lbl}>Skills</div>
            <input value={skillInput} onChange={(e) => setSkillInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addSkill(); } }} placeholder="Type a skill and press Enter" style={inputStyle} />
            {d.skills.length > 0 && (
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 10 }}>
                {d.skills.map((s) => <span key={s} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "7px 11px", borderRadius: 999, background: "var(--clay)", color: "#fff", fontSize: 13, fontWeight: 600 }}>{s}<button onClick={() => removeSkill(s)} style={{ background: "none", border: "none", color: "#fff", cursor: "pointer", padding: 0, opacity: 0.85 }}>✕</button></span>)}
              </div>
            )}
            <div style={{ display: "flex", flexWrap: "wrap", gap: 7, marginTop: 10 }}>
              {SKILL_SUGGEST.filter((s) => !d.skills.includes(s)).slice(0, 6).map((s) => <Chip key={s} onClick={() => addSkill(s)}>+ {s}</Chip>)}
            </div>
          </div>

          {/* availability */}
          <div>
            <div style={lbl}>Availability</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 7, marginBottom: 10 }}>
              {AVAIL_DAYS.map(([v, l]) => <Chip key={v} active={d.availabilityDays.includes(v)} onClick={() => toggleDay(v)}>{l}</Chip>)}
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>
              {AVAIL_HOURS.map(([v, l]) => <Chip key={v} active={d.availabilityHours === v} onClick={() => set("availabilityHours", d.availabilityHours === v ? "" : v)}>{l} hrs</Chip>)}
            </div>
          </div>

          {/* travel */}
          <div>
            <div style={lbl}>Travel & transport</div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 7, marginBottom: 10 }}>
              {TRAVEL_RADII.map(([v, l]) => <Chip key={v} active={d.travelRadius === v} onClick={() => set("travelRadius", d.travelRadius === v ? "" : v)}>{l}</Chip>)}
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>
              {VEHICLES.map(([v, l]) => <Chip key={v} active={d.vehicle === v} onClick={() => set("vehicle", d.vehicle === v ? "" : v)}>{l}</Chip>)}
            </div>
          </div>
        </div>
        <div style={{ padding: "18px 26px", borderTop: "1px solid var(--line)", display: "flex", flexDirection: "column", gap: 10, position: "sticky", bottom: 0, background: "var(--surface)", zIndex: 1 }}>
          {error && <div style={{ color: "var(--clay)", fontSize: 14, fontWeight: 600, display: "flex", gap: 7, alignItems: "flex-start", lineHeight: 1.4 }}><Icon name="bolt" size={15} style={{ flexShrink: 0, marginTop: 1 }} /> {error}</div>}
          <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", width: "100%" }}>
            <Button variant="ghost" onClick={onClose}>Cancel</Button>
            <Button icon="check" onClick={() => {
              if (!d.name || !d.name.trim()) { setError("Name is required."); return; }
              if (!d.phone || !d.phone.trim()) { setError("Phone number is required so that users can contact you for tasks."); return; }
              if (d.phone.replace(/\D/g, "").length !== 10) { setError("Phone number must be exactly 10 digits."); return; }
              if (!d.city || !d.city.trim()) { setError("City is required."); return; }
              onSave(d);
            }}>Save changes</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Reusable rich-profile details (skills / availability / travel / bio) ── */
const _pTag = { display: "inline-flex", alignItems: "center", padding: "7px 13px", borderRadius: 999, background: "var(--clay)", color: "#fff", fontSize: 13.5, fontWeight: 600 };
const _pTagLight = { display: "inline-flex", alignItems: "center", padding: "7px 13px", borderRadius: 999, background: "var(--ink-3)", color: "var(--ink)", fontSize: 13.5, fontWeight: 600 };
const _pSection = { fontFamily: "var(--display)", fontWeight: 600, fontSize: 19, letterSpacing: "-0.02em", color: "var(--ink)", margin: "26px 0 12px" };
function _labelFrom(pairs, value) { const m = (pairs || []).find(([v]) => v === value); return m ? m[1] : value; }

function ProfileDetails({ profile, showBio }) {
  const skills = profile?.skills || [], days = profile?.availabilityDays || [], hours = profile?.availabilityHours || "", travel = profile?.travelRadius || "", vehicle = profile?.vehicle || "";
  const hasAvail = days.length > 0 || hours;
  const hasTravel = travel || (vehicle && vehicle !== "none");
  if (!(showBio && profile?.bio) && skills.length === 0 && !hasAvail && !hasTravel) return null;
  return (
    <div>
      {showBio && profile?.bio && (<><div style={_pSection}>About</div><p style={{ margin: 0, fontSize: 15.5, lineHeight: 1.6, color: "var(--ink)" }}>{profile.bio}</p></>)}
      {skills.length > 0 && (<><div style={_pSection}>Skills</div><div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>{skills.map(s => <span key={s} style={_pTag}>{s}</span>)}</div></>)}
      {hasAvail && (<><div style={_pSection}>Availability</div><div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" }}>{days.map(d => <span key={d} style={_pTagLight}>{_labelFrom(AVAIL_DAYS, d)}</span>)}{hours && <span style={{ fontSize: 14, color: "var(--ink-2)", fontWeight: 600 }}>{_labelFrom(AVAIL_HOURS, hours)} hrs/week</span>}</div></>)}
      {hasTravel && (<><div style={_pSection}>Travel & transport</div><div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>{travel && <span style={_pTagLight}>{_labelFrom(TRAVEL_RADII, travel)}</span>}{vehicle && vehicle !== "none" && <span style={_pTagLight}>{_labelFrom(VEHICLES, vehicle)}</span>}</div></>)}
    </div>
  );
}

/* ── Public profile (view any person's rating + reviews) ───── */
function PublicProfile({ go, userId, demoMode, onMessage, currentUserId, verification, onNeedVerify }) {
  const seed = demoMode ? PEOPLE[userId] : null;
  const [person, setPerson] = useP1(seed || null);
  const [reviews, setReviews] = useP1(demoMode ? (PERSON_REVIEWS[userId] || []) : null);
  const [loading, setLoading] = useP1(!demoMode);

  React.useEffect(() => {
    if (demoMode) return;
    let alive = true;
    setLoading(true);
    Promise.all([Profiles.get(userId), Reviews.forUser(userId)]).then(([p, r]) => {
      if (!alive) return;
      setPerson(p.profile);
      setReviews(r.reviews || []);
      setLoading(false);
    });
    return () => { alive = false; };
  }, [userId, demoMode]);

  const back = (
    <button onClick={() => go("browse")} 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: 16 }}>
      <Icon name="back" size={17} /> Back
    </button>
  );

  if (loading || !person) {
    return <Wrap style={{ paddingTop: 40, paddingBottom: 60, maxWidth: 720 }}>{back}
      <div style={{ color: "var(--ink-2)", fontSize: 15, padding: "40px 0", textAlign: "center" }}>{loading ? "Loading profile…" : "Profile not found."}</div>
    </Wrap>;
  }

  const revs = reviews || [];
  const avg = revs.length ? (revs.reduce((s, r) => s + r.stars, 0) / revs.length) : (person.rating || 0);
  const isMe = userId === currentUserId || userId === "__me";
  const dist = [5, 4, 3, 2, 1].map(n => ({ n, count: revs.filter(r => r.stars === n).length }));
  const maxCount = Math.max(1, ...dist.map(d => d.count));

  // track record tiles
  const stats = demoMode ? (PERSON_STATS[userId] || {}) : {};
  const tiles = [
    { label: "Tasks completed", value: person.jobs ?? 0, color: "var(--ink)" },
    stats.completionRate != null ? { label: "Completion rate", value: stats.completionRate + "%", color: "var(--green)" } : null,
    stats.onTime != null ? { label: "On-time", value: stats.onTime + "%", color: "var(--ink)" } : null,
    { label: "Rated by", value: revs.length ? `${revs.length} ${revs.length === 1 ? "person" : "people"}` : "—", color: "var(--ink)" },
  ].filter(Boolean);

  return (
    <Wrap style={{ paddingTop: 32, paddingBottom: 56, maxWidth: 720 }}>
      {back}

      {/* header */}
      <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 20, padding: 28 }}>
        <div style={{ display: "flex", gap: 18, alignItems: "center", flexWrap: "wrap" }}>
          <Avatar name={person.name} size={76} ring src={person.avatarUrl} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
              <h1 style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 28, letterSpacing: "-0.03em", margin: 0, color: "var(--ink)" }}>{person.name}</h1>
              {person.verified && <VerifiedTick size={20} />}
            </div>
            <div style={{ display: "flex", gap: 18, marginTop: 10, fontSize: 14.5, color: "var(--ink-2)", flexWrap: "wrap" }}>
              {person.city && <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="pin" size={15} /> {person.city}</span>}
              <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="check" size={15} /> {person.jobs ?? 0} tasks done</span>
            </div>
          </div>
          {!isMe && (
            <Button icon="chat" onClick={() => onMessage && onMessage(userId)}>Message</Button>
          )}
        </div>
      </div>

      {/* track record */}
      {tiles.length > 0 && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(130px, 1fr))", gap: 12, marginTop: 16 }}>
          {tiles.map(t => (
            <div key={t.label} style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 14, padding: "16px 14px", textAlign: "center" }}>
              <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 24, color: t.color, letterSpacing: "-0.02em" }}>{t.value}</div>
              <div style={{ fontSize: 12.5, color: "var(--ink-2)", marginTop: 4, fontWeight: 600 }}>{t.label}</div>
            </div>
          ))}
        </div>
      )}

      {/* rating summary */}
      <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 18, padding: 24, marginTop: 16, display: "flex", gap: 32, alignItems: "center", flexWrap: "wrap" }}>
        <div style={{ textAlign: "center", flexShrink: 0 }}>
          <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 52, lineHeight: 1, color: "var(--ink)", letterSpacing: "-0.03em" }}>{avg.toFixed(1)}</div>
          <div style={{ marginTop: 8 }}><Stars value={avg} size={16} /></div>
          <div style={{ fontSize: 13, color: "var(--ink-2)", marginTop: 6 }}>{revs.length} review{revs.length !== 1 ? "s" : ""}</div>
        </div>
        <div style={{ flex: 1, minWidth: 200, display: "flex", flexDirection: "column", gap: 6 }}>
          {dist.map(({ n, count }) => (
            <div key={n} style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{ fontSize: 12.5, color: "var(--ink-2)", width: 28, display: "inline-flex", alignItems: "center", gap: 3 }}>{n}<Icon name="star" size={11} fill stroke={0} style={{ color: "var(--amber)" }} /></span>
              <div style={{ flex: 1, height: 7, background: "var(--ink-3)", borderRadius: 999, overflow: "hidden" }}>
                <div style={{ height: "100%", width: `${(count / maxCount) * 100}%`, background: "var(--amber)", borderRadius: 999 }} />
              </div>
              <span style={{ fontSize: 12.5, color: "var(--ink-2)", width: 18, textAlign: "right" }}>{count}</span>
            </div>
          ))}
        </div>
      </div>

      {/* skills / availability / travel / bio */}
      <ProfileDetails profile={person} showBio />

      {/* work history */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, margin: "32px 0 16px", flexWrap: "wrap" }}>
        <h3 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 22, letterSpacing: "-0.02em", color: "var(--ink)", margin: 0 }}>Work history</h3>
        {revs.length > 0 && <span style={{ fontSize: 13.5, color: "var(--ink-2)" }}>{revs.length} completed {revs.length === 1 ? "task" : "tasks"} reviewed</span>}
      </div>
      {revs.length === 0 ? (
        <div style={{ textAlign: "center", padding: "48px 20px", background: "var(--surface)", border: "1px dashed var(--line-dk)", borderRadius: 18, color: "var(--ink-2)", fontSize: 15 }}>
          No completed work yet — {person.name.split(" ")[0]} hasn't finished a reviewed task.
        </div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {revs.map(r => (
            <div key={r.id} style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 16, padding: "16px 20px" }}>
              {/* task + completed badge + rating */}
              <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
                <div style={{ display: "flex", gap: 11, alignItems: "center", minWidth: 0 }}>
                  <span style={{ width: 30, height: 30, borderRadius: 9, background: "var(--green-3)", color: "var(--green)", display: "grid", placeItems: "center", flexShrink: 0 }}>
                    <Icon name="check" size={16} stroke={2.6} />
                  </span>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 15, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.task || "Completed task"}</div>
                    <div style={{ fontSize: 12.5, color: "var(--green)", fontWeight: 600 }}>Completed{r.when ? ` · ${r.when}` : ""}</div>
                  </div>
                </div>
                <div style={{ flexShrink: 0 }}><Stars value={r.stars} size={14} /></div>
              </div>
              {/* client feedback */}
              {r.text && (
                <div style={{ display: "flex", gap: 10, alignItems: "flex-start", marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--line)" }}>
                  <Avatar name={r.from} size={30} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, lineHeight: 1.5, color: "var(--ink)" }}>{r.text}</div>
                    <div style={{ fontSize: 12.5, color: "var(--ink-2)", marginTop: 4, fontWeight: 600 }}>— {r.from}</div>
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </Wrap>
  );
}

/* ── Legal page (Terms / Privacy) ──────────────────────────── */
function LegalPage({ go, doc }) {
  const [tab, setTab] = useP1(doc === "privacy" ? "privacy" : "terms");
  React.useEffect(() => { if (doc) setTab(doc === "privacy" ? "privacy" : "terms"); }, [doc]);

  const TERMS = [
    ["1. Who we are", "TaskPe is a marketplace that connects people who need real-world tasks done (posters) with people willing to do them (workers). We provide the platform; the agreement for each task is between the poster and the worker."],
    ["2. Eligibility", "You must be at least 18 and able to form a binding contract. Paid tasks require identity verification before you can apply."],
    ["3. Your responsibilities", "Provide accurate information, complete tasks you accept, and treat others with respect. Don't post or accept anything illegal, unsafe, or that violates someone's rights."],
    ["4. Payments & escrow", "For paid tasks, the poster's payment is held until they confirm the work is done, at which point it's released to the worker. If a task is cancelled before completion, the held amount is refunded to the poster. A platform fee may apply."],
    ["5. Cancellations & disputes", "Posters may cancel and be refunded before work is confirmed complete. Workers may withdraw before or after being accepted. Where there's a disagreement, our team may review evidence from both sides."],
    ["6. Liability", "We're a platform, not the employer or contractor. We don't guarantee the quality, safety, or legality of tasks or the conduct of users. Use your judgement and meet in safe, public places where possible."],
    ["7. Account termination", "We may suspend or remove accounts that break these terms, attempt fraud, or harm the community."],
  ];
  const PRIVACY = [
    ["1. What we collect", "Account details (name, email, phone, city), profile info you add (skills, availability, photo, bio), task and message activity, and — for verification — a government ID (Aadhaar), a selfie, a short video, and a UPI ID."],
    ["2. How we use it", "To run the marketplace: match tasks, verify identity, enable payments and messaging, prevent fraud, and improve the service."],
    ["3. Identity documents", "Your Aadhaar image, selfie and video are stored privately and viewed only by our review team via short-lived secure links. We store only the last 4 digits of the Aadhaar number, never the full number."],
    ["4. Sharing", "We share only what's needed to complete a task — e.g. your name, rating and city are visible to the other party. We don't sell your personal data. Payment processing is handled by our payment partner."],
    ["5. Retention", "We keep verification documents only as long as needed to maintain your verified status and meet legal obligations, then delete them."],
    ["6. Your rights", "You can view and edit your profile any time, request a copy of your data, or ask us to delete your account and personal data, subject to legal retention requirements."],
    ["7. Contact", "Questions about your data? Reach our support team from the app."],
  ];
  const sections = tab === "privacy" ? PRIVACY : TERMS;

  return (
    <Wrap style={{ paddingTop: 32, paddingBottom: 60, maxWidth: 760 }}>
      <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: 16 }}>
        <Icon name="back" size={17} /> Back
      </button>
      <div style={{ display: "inline-flex", background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 12, padding: 4, marginBottom: 24 }}>
        {[["terms", "Terms of Service"], ["privacy", "Privacy Policy"]].map(([v, l]) => (
          <button key={v} onClick={() => setTab(v)} style={{ padding: "9px 18px", borderRadius: 9, border: "none", cursor: "pointer", fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600, background: tab === v ? "var(--ink)" : "transparent", color: tab === v ? "var(--paper)" : "var(--ink-2)" }}>{l}</button>
        ))}
      </div>
      <h1 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: "clamp(28px,4vw,40px)", letterSpacing: "-0.03em", margin: "0 0 6px", color: "var(--ink)" }}>{tab === "privacy" ? "Privacy Policy" : "Terms of Service"}</h1>
      <p style={{ fontSize: 14, color: "var(--ink-2)", margin: "0 0 28px" }}>Last updated June 2026 · A plain-English summary for this prototype.</p>
      <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
        {sections.map(([h, body]) => (
          <div key={h}>
            <h3 style={{ fontFamily: "var(--display)", fontWeight: 600, fontSize: 19, letterSpacing: "-0.02em", color: "var(--ink)", margin: "0 0 8px" }}>{h}</h3>
            <p style={{ fontSize: 15.5, lineHeight: 1.6, color: "var(--ink-2)", margin: 0 }}>{body}</p>
          </div>
        ))}
      </div>
    </Wrap>
  );
}

Object.assign(window, { ProfilePage, PublicProfile, LegalPage });
