// layout.jsx — nav, footer, task card
const { useState: useStateL } = React;

function Logo({ onClick }) {
  return (
    <button onClick={onClick} style={{
      display: "inline-flex", alignItems: "center", gap: 9, cursor: "pointer", background: "none", border: "none",
    }}>
      <span style={{
        width: 30, height: 30, borderRadius: 9, background: "var(--clay)", color: "#fff",
        display: "grid", placeItems: "center", flexShrink: 0,
      }}>
        <Icon name="users" size={18} stroke={2} />
      </span>
      <span className="logo-text" style={{
        fontFamily: "var(--display)", fontWeight: 700, fontSize: 21, letterSpacing: "-0.03em", color: "var(--ink)",
      }}>TaskPe</span>
    </button>
  );
}

function MenuItem({ icon, label, onClick, danger }) {
  const [h, setH] = useStateL(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)} style={{
      display: "flex", alignItems: "center", gap: 11, width: "100%", textAlign: "left",
      background: h ? "var(--ink-3)" : "none", border: "none", cursor: "pointer",
      padding: "10px 12px", borderRadius: 9, fontFamily: "var(--sans)", fontSize: 14.5, fontWeight: 600,
      color: danger ? "var(--clay)" : "var(--ink)",
    }}>
      <Icon name={icon} size={18} stroke={1.8} /> {label}
    </button>
  );
}

function NotifBell({ notifications, unread, onOpen, onClickItem }) {
  const [open, setOpen] = useStateL(false);
  const list = notifications || [];
  const ICON_BY = { application: "users", accepted: "check", rejected: "ban", proof: "doc", released: "wallet", review: "star", verified: "shield", verify_rejected: "shield", message: "chat" };
  const COLOR_BY = { application: "var(--blue)", accepted: "var(--green)", rejected: "var(--clay)", proof: "var(--clay)", released: "var(--green)", review: "var(--amber-dk)", verified: "var(--green)", verify_rejected: "var(--clay)", message: "var(--ink-2)" };
  const toggle = () => { const willOpen = !open; setOpen(willOpen); if (willOpen && onOpen) onOpen(); };
  return (
    <div style={{ position: "relative" }}>
      <button onClick={toggle} title="Notifications" style={{ position: "relative", background: "none", border: "none", cursor: "pointer", color: "var(--ink-2)", padding: 6, display: "grid", placeItems: "center" }}>
        <Icon name="bell" size={22} stroke={1.7} />
        {unread > 0 && (
          <span style={{ position: "absolute", top: 0, right: 0, minWidth: 16, height: 16, padding: "0 3px", borderRadius: 999, background: "var(--clay)", color: "#fff", fontSize: 10, fontWeight: 700, display: "grid", placeItems: "center", fontFamily: "var(--sans)" }}>{unread > 9 ? "9+" : unread}</span>
        )}
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 49 }} />
          <div style={{ position: "absolute", right: 0, top: 46, zIndex: 50, width: 348, maxWidth: "calc(100vw - 32px)", background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 14, boxShadow: "0 16px 40px -14px rgba(20,14,6,.35)", overflow: "hidden" }}>
            <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--line)", fontWeight: 700, fontSize: 14, color: "var(--ink)" }}>Notifications</div>
            <div style={{ maxHeight: 380, overflowY: "auto" }}>
              {list.length === 0 ? (
                <div style={{ padding: "40px 20px", textAlign: "center", color: "var(--ink-2)", fontSize: 14 }}>You're all caught up.</div>
              ) : list.map((n) => (
                <button key={n.id} onClick={() => { onClickItem && onClickItem(n); setOpen(false); }} style={{ display: "flex", gap: 11, alignItems: "flex-start", width: "100%", textAlign: "left", background: n.read ? "none" : "color-mix(in srgb, var(--clay) 5%, transparent)", border: "none", borderBottom: "1px solid var(--line)", cursor: "pointer", padding: "12px 14px" }}>
                  <span style={{ width: 32, height: 32, borderRadius: 9, flexShrink: 0, display: "grid", placeItems: "center", background: "var(--ink-3)", color: COLOR_BY[n.type] || "var(--ink-2)" }}><Icon name={ICON_BY[n.type] || "bell"} size={16} /></span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 700, fontSize: 13.5, color: "var(--ink)" }}>{n.title}</div>
                    <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.4, marginTop: 1 }}>{n.body}</div>
                    {n.time && <div style={{ fontSize: 11.5, color: "var(--ink-2)", marginTop: 4 }}>{timeAgo(n.time)}</div>}
                  </div>
                  {!n.read && <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--clay)", flexShrink: 0, marginTop: 5 }} />}
                </button>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
}

function Nav({ go, view, onPost, savedCount, unreadCount, isAdmin, notifications, notifUnread, onNotifOpen, onNotifClick, canLogout, onLogout, profile, email }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const [profileOpen, setProfileOpen] = useState(false);
  const profileName = profile?.name || ME.name;
  const profileEmail = email || "";
  const links = [
    { id: "browse", label: "Browse tasks", icon: "search" },
    { id: "how", label: "How it works", icon: "doc" },
    { id: "dashboard", label: "My tasks", icon: "users" },
    { id: "saved", label: "Saved", icon: "heart" },
  ];
  const close = () => setMenuOpen(false);

  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 40, background: "color-mix(in srgb, var(--paper) 86%, transparent)",
      backdropFilter: "blur(12px)", borderBottom: "1px solid var(--line)",
    }}>
      <div style={{
        maxWidth: 1200, margin: "0 auto", padding: "13px 24px",
        display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
      }}>
        <Logo onClick={() => { go("home"); close(); }} />

        {/* desktop nav */}
        <nav style={{ display: "flex", alignItems: "center", gap: 4, flex: 1 }} className="nav-links">
          {links.slice(0, canLogout ? 3 : 2).map((l) => (
            <button key={l.id} onClick={() => go(l.id)} style={{
              background: "none", border: "none", cursor: "pointer", padding: "8px 14px",
              fontFamily: "var(--sans)", fontSize: 15, fontWeight: 600, borderRadius: 8,
              color: view === l.id ? "var(--ink)" : "var(--ink-2)",
            }}>{l.label}</button>
          ))}
        </nav>

        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          {canLogout && (
            <>
              {/* saved heart — always visible */}
              <button onClick={() => { go("saved"); close(); }} title="Saved tasks" style={{
                position: "relative", background: "none", border: "none", cursor: "pointer",
                color: view === "saved" ? "var(--clay)" : "var(--ink-2)", padding: 6, display: "grid", placeItems: "center",
              }}>
                <Icon name="heart" size={22} fill={view === "saved"} stroke={view === "saved" ? 0 : 1.7} />
                {savedCount > 0 && (
                  <span style={{ position: "absolute", top: 0, right: 0, width: 16, height: 16, borderRadius: "50%", background: "var(--clay)", color: "#fff", fontSize: 10, fontWeight: 700, display: "grid", placeItems: "center", fontFamily: "var(--sans)" }}>
                    {savedCount > 9 ? "9+" : savedCount}
                  </span>
                )}
              </button>

              {/* notifications bell */}
              <NotifBell notifications={notifications} unread={notifUnread} onOpen={onNotifOpen} onClickItem={onNotifClick} />

              {/* messages icon */}
              <button onClick={() => { go("messages"); close(); }} title="Messages" style={{
                position: "relative", background: "none", border: "none", cursor: "pointer",
                color: view === "messages" ? "var(--clay)" : "var(--ink-2)", padding: 6, display: "grid", placeItems: "center",
              }}>
                <Icon name="chat" size={22} stroke={1.7} />
                {unreadCount > 0 && (
                  <span style={{ position: "absolute", top: 0, right: 0, width: 16, height: 16, borderRadius: "50%", background: "var(--clay)", color: "#fff", fontSize: 10, fontWeight: 700, display: "grid", placeItems: "center", fontFamily: "var(--sans)" }}>
                    {unreadCount > 9 ? "9+" : unreadCount}
                  </span>
                )}
              </button>
            </>
          )}

          {/* post button — icon only on mobile, icon+text on desktop */}
          <button onClick={onPost} style={{
            display: "inline-flex", alignItems: "center", gap: 7,
            padding: "8px 14px", borderRadius: "var(--r-btn)", fontWeight: 600, cursor: "pointer",
            fontFamily: "var(--sans)", fontSize: 14, background: "var(--clay)", color: "#fff", border: "1px solid transparent",
          }}>
            <Icon name="plus" size={16} />
            <span className="nav-post-label">Post a task</span>
          </button>

          {/* avatar — opens profile dropdown */}
          {!canLogout && isSupabaseConfigured() ? (
            <Button size="sm" onClick={() => go("profile")}>Sign in</Button>
          ) : (
            <div style={{ position: "relative" }}>
              <button onClick={() => setProfileOpen((o) => !o)} style={{ background: "none", border: "none", cursor: "pointer", padding: 0, display: "grid", placeItems: "center" }}>
                <Avatar name={profileName === "You" ? "You Me" : profileName} size={36} src={profile?.avatarUrl} />
              </button>
              {profileOpen && (
                <>
                  <div onClick={() => setProfileOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 49 }} />
                  <div style={{ position: "absolute", right: 0, top: 46, zIndex: 50, width: 230, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 14, boxShadow: "0 16px 40px -14px rgba(20,14,6,.35)", overflow: "hidden", padding: 6 }}>
                    <div style={{ padding: "10px 12px 12px", borderBottom: "1px solid var(--line)", marginBottom: 6 }}>
                      <div style={{ fontWeight: 700, fontSize: 14.5, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{profileName}</div>
                      {profileEmail && <div style={{ fontSize: 12.5, color: "var(--ink-2)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", marginTop: 2 }}>{profileEmail}</div>}
                    </div>
                    <MenuItem icon="users" label="My tasks" onClick={() => { go("dashboard"); setProfileOpen(false); }} />
                    <MenuItem icon="wallet" label="Wallet" onClick={() => { go("wallet"); setProfileOpen(false); }} />
                    <MenuItem icon="settings" label="Profile & settings" onClick={() => { go("profile"); setProfileOpen(false); }} />
                    {isAdmin && <MenuItem icon="shield" label="Admin console" onClick={() => { window.location.href = "/admin.html"; }} />}
                    <MenuItem icon="logout" label="Log out" danger onClick={() => { onLogout && onLogout(); setProfileOpen(false); }} />
                  </div>
                </>
              )}
            </div>
          )}

          {/* hamburger — mobile only */}
          <button className="nav-hamburger" onClick={() => setMenuOpen((o) => !o)} style={{
            background: "var(--ink-3)", border: "none", borderRadius: 9, width: 38, height: 38,
            display: "none", alignItems: "center", justifyContent: "center", cursor: "pointer", color: "var(--ink)", flexShrink: 0,
          }}>
            <svg width={20} height={20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round">
              {menuOpen
                ? <><path d="M6 6l12 12M6 18L18 6" /></>
                : <><path d="M4 7h16M4 12h16M4 17h16" /></>}
            </svg>
          </button>
        </div>
      </div>

      {/* mobile dropdown menu */}
      {menuOpen && (
        <div style={{
          background: "var(--surface)", borderTop: "1px solid var(--line)",
          padding: "12px 16px 20px",
        }}>
          {links.slice(0, canLogout ? 4 : 2).map((l) => (
            <button key={l.id} onClick={() => { go(l.id); close(); }} style={{
              display: "flex", alignItems: "center", gap: 12, width: "100%",
              background: view === l.id ? "var(--ink-3)" : "none", border: "none", cursor: "pointer",
              padding: "13px 14px", borderRadius: 12, fontFamily: "var(--sans)", fontSize: 16,
              fontWeight: 600, color: view === l.id ? "var(--ink)" : "var(--ink-2)", marginBottom: 2,
              textAlign: "left",
            }}>
              <Icon name={l.icon} size={20} stroke={1.7} />
              {l.label}
              {l.id === "saved" && savedCount > 0 && (
                <span style={{ marginLeft: "auto", fontSize: 12, fontWeight: 700, background: "var(--clay)", color: "#fff", padding: "2px 8px", borderRadius: 999 }}>
                  {savedCount}
                </span>
              )}
            </button>
          ))}
          {canLogout ? (
            <>
              <button onClick={() => { go("messages"); close(); }} style={{
                display: "flex", alignItems: "center", gap: 12, width: "100%",
                background: view === "messages" ? "var(--ink-3)" : "none", border: "none", cursor: "pointer",
                padding: "13px 14px", borderRadius: 12, fontFamily: "var(--sans)", fontSize: 16,
                fontWeight: 600, color: view === "messages" ? "var(--ink)" : "var(--ink-2)", textAlign: "left",
              }}>
                <Icon name="chat" size={20} stroke={1.7} /> Messages
                {unreadCount > 0 && (
                  <span style={{ marginLeft: "auto", fontSize: 12, fontWeight: 700, background: "var(--clay)", color: "#fff", padding: "2px 8px", borderRadius: 999 }}>
                    {unreadCount}
                  </span>
                )}
              </button>

              <button onClick={() => { go("wallet"); close(); }} style={{
                display: "flex", alignItems: "center", gap: 12, width: "100%",
                background: view === "wallet" ? "var(--ink-3)" : "none", border: "none", cursor: "pointer",
                padding: "13px 14px", borderRadius: 12, fontFamily: "var(--sans)", fontSize: 16,
                fontWeight: 600, color: view === "wallet" ? "var(--ink)" : "var(--ink-2)", textAlign: "left",
              }}>
                <Icon name="wallet" size={20} stroke={1.7} /> Wallet
              </button>

              <button onClick={() => { go("profile"); close(); }} style={{
                display: "flex", alignItems: "center", gap: 12, width: "100%",
                background: view === "profile" ? "var(--ink-3)" : "none", border: "none", cursor: "pointer",
                padding: "13px 14px", borderRadius: 12, fontFamily: "var(--sans)", fontSize: 16,
                fontWeight: 600, color: view === "profile" ? "var(--ink)" : "var(--ink-2)", textAlign: "left",
              }}>
                <Icon name="settings" size={20} stroke={1.7} /> Profile & settings
              </button>
              <button onClick={() => { onLogout && onLogout(); close(); }} style={{
                display: "flex", alignItems: "center", gap: 12, width: "100%",
                background: "none", border: "none", cursor: "pointer", marginTop: 4,
                padding: "13px 14px", borderRadius: 12, fontFamily: "var(--sans)", fontSize: 16,
                fontWeight: 600, color: "var(--clay)", textAlign: "left", borderTop: "1px solid var(--line)",
              }}>
                <Icon name="logout" size={20} stroke={1.7} /> Log out
              </button>
            </>
          ) : (
            <button onClick={() => { go("profile"); close(); }} style={{
              display: "flex", alignItems: "center", gap: 12, width: "100%",
              background: "none", border: "none", cursor: "pointer", marginTop: 4,
              padding: "13px 14px", borderRadius: 12, fontFamily: "var(--sans)", fontSize: 16,
              fontWeight: 600, color: "var(--clay)", textAlign: "left", borderTop: "1px solid var(--line)",
            }}>
              <Icon name="logout" size={20} stroke={1.7} /> Sign in
            </button>
          )}
        </div>
      )}
    </header>
  );
}

function TaskCard({ task, onClick, onSave, saved }) {
  const [h, setH] = useStateL(false);
  const p = PEOPLE[task.poster] || task.posterProfile || { name: "Someone", handle: "@user", city: "", verified: false, rating: 0, jobs: 0 };
  const c = CAT[task.cat] || { label: task.cat, icon: "search" };
  const dl = deadlineInfo(task.deadline);
  return (
    <article onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{
        background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--r-card)",
        padding: 20, cursor: "pointer", transition: "transform .15s, box-shadow .15s, border-color .15s",
        transform: h ? "translateY(-3px)" : "none",
        boxShadow: h ? "0 14px 30px -16px rgba(40,30,15,.35)" : "0 1px 2px rgba(40,30,15,.04)",
        borderColor: h ? "var(--line-dk)" : "var(--line)",
        display: "flex", flexDirection: "column", gap: 14, position: "relative",
      }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
        <span style={{
          display: "inline-flex", alignItems: "center", gap: 7, fontSize: 12.5, fontWeight: 700,
          color: "var(--ink-2)", textTransform: "uppercase", letterSpacing: "0.04em",
        }}>
          <Icon name={c.icon} size={15} stroke={1.9} /> {c.label}
        </span>
        {task.urgent && (
          <span style={{
            display: "inline-flex", alignItems: "center", gap: 4, fontSize: 11.5, fontWeight: 700,
            color: "var(--clay)", background: "color-mix(in srgb, var(--clay) 12%, transparent)",
            padding: "3px 9px", borderRadius: 999,
          }}><Icon name="bolt" size={12} fill stroke={0} /> Urgent</span>
        )}
      </div>

      <h3 style={{
        fontFamily: "var(--display)", fontWeight: 600, fontSize: 19.5, lineHeight: 1.18,
        letterSpacing: "-0.02em", color: "var(--ink)", margin: 0, textWrap: "balance",
      }}>{task.title}</h3>

      <div style={{ display: "flex", alignItems: "center", gap: 14, color: "var(--ink-2)", fontSize: 13.5, fontWeight: 500, flexWrap: "wrap" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <Icon name={task.remote ? "bolt" : "pin"} size={14} /> {task.city}
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <Icon name="users" size={14} /> {task.applicants} applied
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <Icon name="clock" size={14} /> {task.posted} ago
        </span>
        {dl && (
          <span style={{ display: "inline-flex", alignItems: "center", gap: 5, color: dl.overdue ? "var(--clay)" : dl.soon ? "var(--amber-dk)" : "var(--ink-2)", fontWeight: dl.overdue || dl.soon ? 700 : 500 }}>
            <Icon name="bolt" size={14} fill={dl.overdue || dl.soon} stroke={dl.overdue || dl.soon ? 0 : 1.7} /> {dl.short}
          </span>
        )}
      </div>

      <div style={{ height: 1, background: "var(--line)", margin: "2px 0" }} />

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, minWidth: 0 }}>
          <Avatar name={p.name} size={30} />
          <span style={{ display: "flex", alignItems: "center", gap: 5, minWidth: 0 }}>
            <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{p.name}</span>
            {p.verified && <VerifiedTick size={14} />}
          </span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <PayTag pay={task.pay} />
          {onSave && (
            <button
              onClick={(e) => { e.stopPropagation(); onSave(task.id); }}
              title={saved ? "Remove from saved" : "Save task"}
              style={{ background: "none", border: "none", cursor: "pointer", padding: 4, color: saved ? "var(--clay)" : "var(--ink-2)", flexShrink: 0, display: "grid", placeItems: "center" }}
            >
              <Icon name="heart" size={17} fill={!!saved} stroke={saved ? 0 : 1.7} />
            </button>
          )}
        </div>
      </div>
    </article>
  );
}

function Footer({ go, isAdmin }) {
  const cols = [
    {
      title: "Marketplace",
      items: [
        { label: "Browse tasks", action: () => go("browse") },
        { label: "Post a task", action: () => go("post") },
        { label: "How it works", action: () => go("how") },
      ],
    },
    {
      title: "Humans",
      items: [
        { label: "Sign in / Profile", action: () => go("profile") },
        { label: "Verify identity", action: () => go("verify") },
        { label: "My dashboard", action: () => go("dashboard") },
      ],
    },
  ];
  return (
    <footer style={{ background: "var(--ink)", color: "var(--paper)", marginTop: 80 }}>
      <div style={{ maxWidth: 1200, margin: "0 auto", padding: "56px 24px 40px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 40 }}>
          <div style={{ maxWidth: 300 }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 9, marginBottom: 14 }}>
              <span style={{ width: 30, height: 30, borderRadius: 9, background: "var(--clay)", display: "grid", placeItems: "center" }}>
                <Icon name="users" size={18} stroke={2} style={{ color: "#fff" }} />
              </span>
              <span style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 21, letterSpacing: "-0.03em" }}>TaskPe</span>
            </span>
            <p style={{ color: "color-mix(in srgb, var(--paper) 65%, transparent)", fontSize: 14.5, lineHeight: 1.55, margin: 0 }}>
              People helping people get real-world things done. No bots, no AI — just humans.
            </p>
          </div>
          <div style={{ display: "flex", gap: 80, flexWrap: "wrap" }}>
            {cols.map((col) => (
              <div key={col.title}>
                <div style={{ fontSize: 12.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "color-mix(in srgb, var(--paper) 55%, transparent)", marginBottom: 14 }}>{col.title}</div>
                <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 10 }}>
                  {col.items.map((item) => (
                    <li key={item.label}>
                      <a onClick={item.action} style={{ color: "color-mix(in srgb, var(--paper) 80%, transparent)", textDecoration: "none", fontSize: 14.5, cursor: "pointer" }}>
                        {item.label}
                      </a>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </div>
        <div style={{ marginTop: 48, paddingTop: 22, borderTop: "1px solid color-mix(in srgb, var(--paper) 16%, transparent)", display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 12, color: "color-mix(in srgb, var(--paper) 55%, transparent)", fontSize: 13.5 }}>
          <span>© 2026 TaskPe · A prototype</span>
          <span style={{ display: "flex", gap: 22 }}>
            <a onClick={() => go("legal", { doc: "terms" })} style={{ color: "inherit", textDecoration: "none", cursor: "pointer" }}>Terms</a>
            <a onClick={() => go("legal", { doc: "privacy" })} style={{ color: "inherit", textDecoration: "none", cursor: "pointer" }}>Privacy</a>
            <a href="mailto:hiringahuman@gmail.com" style={{ color: "inherit", textDecoration: "none" }}>Contact Support</a>
            {isAdmin && <a href="/admin.html" style={{ color: "inherit", textDecoration: "none", cursor: "pointer", opacity: 0.7 }}>Admin</a>}
          </span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Logo, Nav, TaskCard, Footer });
