/* global React, Icon, Logo */
const { useState: useStateSearch } = React;

// shared dataset
const ROOMS = [
  { id: "rm-001", title: "Sunny private room near MLK station", area: "West Oakland, CA", host: "Dana K.", price: 685, type: "Private room", beds: 1, tone: "a", tags: ["Vouchers", "Pet OK", "Furnished"], rating: 4.9, reviews: 47, avail: "May 8" },
  { id: "rm-002", title: "Quiet upstairs room, shared kitchen", area: "Bushrod, Oakland", host: "Marco V.", price: 540, type: "Private room", beds: 1, tone: "b", tags: ["Sober living", "Vouchers"], rating: 4.8, reviews: 31, avail: "May 5" },
  { id: "rm-003", title: "Ground-floor accessible room", area: "Fruitvale, Oakland", host: "Ana R.", price: 720, type: "Private room", beds: 1, tone: "c", tags: ["Wheelchair", "Vouchers"], rating: 5.0, reviews: 22, avail: "May 12" },
  { id: "rm-004", title: "Shared room in 4-bed home", area: "East Oakland", host: "Jamal P.", price: 320, type: "Shared room", beds: 2, tone: "d", tags: ["Women only", "Sober living"], rating: 4.7, reviews: 64, avail: "May 4" },
  { id: "rm-005", title: "Studio with private bath", area: "Adams Point", host: "Theo M.", price: 980, type: "Studio", beds: 1, tone: "e", tags: ["Vouchers", "Furnished"], rating: 4.9, reviews: 18, avail: "May 15" },
  { id: "rm-006", title: "Cozy room in family duplex", area: "Temescal, Oakland", host: "Priya S.", price: 610, type: "Private room", beds: 1, tone: "a", tags: ["Pet OK", "Furnished"], rating: 4.8, reviews: 39, avail: "May 7" },
  { id: "rm-007", title: "Re-entry housing room", area: "San Antonio, Oakland", host: "Reach Forward", price: 410, type: "Private room", beds: 1, tone: "b", tags: ["Re-entry", "Sober living"], rating: 4.9, reviews: 91, avail: "Now" },
  { id: "rm-008", title: "Veteran preferred private room", area: "Lakeshore, Oakland", host: "James W.", price: 750, type: "Private room", beds: 1, tone: "c", tags: ["HUD-VASH", "Vouchers"], rating: 4.9, reviews: 28, avail: "May 6" },
];
window.ROOMS = ROOMS;

const PageSearch = ({ onNav }) => {
  const [view, setView] = useStateSearch("grid");
  const [active, setActive] = useStateSearch(["Vouchers"]);
  const filters = ["Vouchers", "Sober living", "Wheelchair", "Pet OK", "Women only", "HUD-VASH", "Re-entry", "Furnished", "Short term"];
  const toggle = (t) => setActive(a => a.includes(t) ? a.filter(x => x !== t) : [...a, t]);

  return (
    <main className="page-main">
      {/* Refined search bar */}
      <div style={{ borderBottom: "1px solid var(--line-1)", background: "var(--bg-0)", position: "sticky", top: 68, zIndex: 30 }}>
        <div className="container" style={{ padding: "20px 32px" }}>
          <div className="row gap-3" style={{ flexWrap: "wrap" }}>
            <div className="card row" style={{ padding: 4, gap: 0, borderRadius: 999, flex: 1, minWidth: 480 }}>
              <div className="row gap-2" style={{ padding: "8px 18px", flex: 1 }}>
                <Icon name="pin" className="i i-sm" style={{ color: "var(--accent)" }} />
                <span className="t-sm">Oakland, CA</span>
              </div>
              <span className="v-divider" style={{ height: 24 }} />
              <div className="row gap-2 muted" style={{ padding: "8px 18px" }}>
                <Icon name="calendar" className="i i-sm" />
                <span className="t-sm">Anytime</span>
              </div>
              <span className="v-divider" style={{ height: 24 }} />
              <div className="row gap-2 muted" style={{ padding: "8px 18px" }}>
                <Icon name="cash" className="i i-sm" />
                <span className="t-sm">Up to $1,000</span>
              </div>
              <button className="btn btn-primary" style={{ borderRadius: 999, height: 40 }}>
                <Icon name="search" className="i i-sm" /> Update
              </button>
            </div>
            <button className="btn btn-outline">
              <Icon name="filter" className="i i-sm" /> All filters · 3
            </button>
            <div className="pill-tab-row">
              <button className={`pill-tab ${view === "grid" ? "active" : ""}`} onClick={() => setView("grid")}><Icon name="grid" className="i i-sm" style={{ verticalAlign: "middle", marginRight: 6 }} />Grid</button>
              <button className={`pill-tab ${view === "map" ? "active" : ""}`} onClick={() => setView("map")}><Icon name="map" className="i i-sm" style={{ verticalAlign: "middle", marginRight: 6 }} />Map</button>
            </div>
          </div>
          <div className="scroll-x" style={{ marginTop: 14 }}>
            {filters.map(f => (
              <span key={f} className={`chip ${active.includes(f) ? "active" : ""}`} onClick={() => toggle(f)}>{f}</span>
            ))}
          </div>
        </div>
      </div>

      {view === "grid" ? (
        <section className="container" style={{ padding: "32px 0 80px" }}>
          <div className="row spread" style={{ marginBottom: 24 }}>
            <h2 className="t-h1">{ROOMS.length} rooms in Oakland</h2>
            <div className="row gap-3 t-sm muted">
              <span>Sort by</span>
              <button className="btn btn-sm btn-outline">Best match <Icon name="chevDown" className="i i-sm" /></button>
            </div>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 24 }}>
            {ROOMS.map(r => <RoomCard key={r.id} r={r} onClick={() => onNav("listing", { id: r.id })} />)}
          </div>
        </section>
      ) : (
        <section style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 0, height: "calc(100vh - 180px)" }}>
          <div style={{ overflow: "auto", padding: "24px 32px", display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16, alignContent: "start" }}>
            {ROOMS.map(r => <RoomCard key={r.id} r={r} compact onClick={() => onNav("listing", { id: r.id })} />)}
          </div>
          <MapPlaceholder />
        </section>
      )}
    </main>
  );
};

const RoomCard = ({ r, onClick, compact }) => (
  <article className="col gap-3" style={{ cursor: "pointer" }} onClick={onClick}>
    <div className={`photo has-img`} style={{ aspectRatio: compact ? "1.2" : "1", borderRadius: 14, backgroundImage: `url(${window.ROOM_IMG[ROOMS.indexOf(r) % window.ROOM_IMG.length]})` }}>
      <span className="badge" style={{ position: "absolute", top: 12, left: 12, background: "rgba(0,0,0,0.5)", backdropFilter: "blur(8px)", color: "#fff" }}>
        {r.type === "Shared room" ? "Shared" : r.type}
      </span>
      <button className="btn btn-icon" style={{ position: "absolute", top: 8, right: 8, background: "rgba(0,0,0,0.4)", color: "#fff", height: 36, width: 36 }}>
        <Icon name="heart" className="i i-sm" />
      </button>
      <span style={{ position: "absolute", bottom: 12, left: 12, color: "#fff" }} className="badge badge-success">
        <span className="dot live" /> Available {r.avail}
      </span>
    </div>
    <div className="col gap-1">
      <div className="row spread">
        <h3 className="t-h3" style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1 }}>{r.title}</h3>
        <span className="row gap-1 t-sm" style={{ flex: "none" }}>
          <Icon name="star" className="i i-sm" style={{ color: "var(--accent)" }} /> {r.rating}
        </span>
      </div>
      <p className="t-sm muted">{r.area} · {r.host}</p>
      <div className="row gap-2" style={{ marginTop: 4, flexWrap: "wrap" }}>
        {r.tags.slice(0, 3).map(t => <span key={t} className="chip chip-static" style={{ height: 24, padding: "0 8px", fontSize: 11 }}>{t}</span>)}
      </div>
      <div className="row spread" style={{ marginTop: 8 }}>
        <span className="t-mono" style={{ fontSize: 16 }}>${r.price}<span className="muted t-sm" style={{ fontFamily: "var(--font-sans)" }}> / month</span></span>
        <span className="t-mono-sm muted">{r.reviews} reviews</span>
      </div>
    </div>
  </article>
);

const MapPlaceholder = () => (
  <div style={{ position: "relative", background: "linear-gradient(160deg, oklch(0.20 0.012 240), oklch(0.16 0.01 240))", overflow: "hidden" }}>
    <svg viewBox="0 0 800 800" preserveAspectRatio="xMidYMid slice" style={{ width: "100%", height: "100%", opacity: 0.25 }}>
      <defs>
        <pattern id="g" width="40" height="40" patternUnits="userSpaceOnUse"><path d="M40 0H0V40" stroke="var(--ink-3)" strokeWidth="0.5" fill="none"/></pattern>
      </defs>
      <rect width="800" height="800" fill="url(#g)" />
      <path d="M0 320 Q200 280 400 340 T800 320" stroke="var(--accent)" strokeWidth="2" fill="none" opacity="0.5"/>
      <path d="M0 480 Q200 440 400 500 T800 480" stroke="var(--info)" strokeWidth="2" fill="none" opacity="0.5"/>
      <path d="M320 0 L380 800" stroke="var(--ink-3)" strokeWidth="1" />
      <path d="M520 0 L460 800" stroke="var(--ink-3)" strokeWidth="1" />
    </svg>
    {[
      [220, 280, 685], [380, 220, 540], [560, 320, 720], [320, 480, 320],
      [480, 540, 980], [600, 460, 610], [240, 600, 410], [440, 380, 750]
    ].map(([x, y, p], i) => (
      <div key={i} style={{ position: "absolute", left: `${x/8}%`, top: `${y/8}%`, transform: "translate(-50%, -50%)" }}>
        <span className="t-mono" style={{ background: "var(--bg-0)", color: "var(--ink-0)", padding: "6px 10px", borderRadius: 999, boxShadow: "0 0 0 1px var(--line-2), 0 6px 16px -4px rgba(0,0,0,0.5)", fontSize: 12 }}>
          ${p}
        </span>
      </div>
    ))}
    <div style={{ position: "absolute", bottom: 24, left: 24, right: 24 }} className="card card-pad row spread">
      <div className="col">
        <span className="t-mono-xs muted">Showing</span>
        <span className="t-h3">8 rooms in viewport</span>
      </div>
      <div className="row gap-2">
        <button className="btn btn-icon btn-outline"><Icon name="plus" /></button>
        <button className="btn btn-icon btn-outline"><Icon name="location" /></button>
      </div>
    </div>
  </div>
);

const PageListing = ({ onNav, params }) => {
  const r = ROOMS.find(x => x.id === params?.id) || ROOMS[0];
  return (
    <main className="page-main container" style={{ padding: "32px 0 80px" }}>
      <button className="btn btn-sm btn-ghost" onClick={() => onNav("search")}><Icon name="arrowLeft" className="i i-sm" /> Back to results</button>

      {/* Title row */}
      <div className="row spread" style={{ margin: "20px 0 16px", alignItems: "flex-end" }}>
        <div className="col gap-2">
          <h1 className="t-display">{r.title}</h1>
          <div className="row gap-3 t-sm muted">
            <span className="row gap-1"><Icon name="star" className="i i-sm" style={{ color: "var(--accent)" }} /> {r.rating} · {r.reviews} reviews</span>
            <span>·</span>
            <span className="row gap-1"><Icon name="pin" className="i i-sm" /> {r.area}</span>
            <span>·</span>
            <span className="row gap-1"><Icon name="shield" className="i i-sm" style={{ color: "var(--info)" }} /> Verified host</span>
          </div>
        </div>
        <div className="row gap-2">
          <button className="btn btn-outline btn-sm"><Icon name="heart" className="i i-sm" /> Save</button>
          <button className="btn btn-outline btn-sm"><Icon name="ext" className="i i-sm" /> Share</button>
          <button className="btn btn-outline btn-sm"><Icon name="flag" className="i i-sm" /> Report</button>
        </div>
      </div>

      {/* Photo grid */}
      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr", gridTemplateRows: "repeat(2, 200px)", gap: 8, borderRadius: 18, overflow: "hidden", marginBottom: 32 }}>
        <div className={`photo has-img`} style={{ gridRow: "span 2", borderRadius: 0, backgroundImage: `url(${window.ROOM_DETAIL_IMGS[0]})` }}></div>
        <div className="photo has-img" style={{ borderRadius: 0, backgroundImage: `url(${window.ROOM_DETAIL_IMGS[1]})` }}></div>
        <div className="photo has-img" style={{ borderRadius: 0, backgroundImage: `url(${window.ROOM_DETAIL_IMGS[2]})` }}></div>
        <div className="photo has-img" style={{ borderRadius: 0, backgroundImage: `url(${window.ROOM_DETAIL_IMGS[3]})` }}></div>
        <div className="photo has-img" style={{ borderRadius: 0, position: "relative", backgroundImage: `url(${window.ROOM_DETAIL_IMGS[4]})` }}>
          <button className="btn btn-secondary btn-sm" style={{ position: "absolute", bottom: 12, right: 12 }}>+12 more</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 380px", gap: 56 }}>
        <div className="col gap-8">
          {/* Host strip */}
          <div className="row spread" style={{ paddingBottom: 24, borderBottom: "1px solid var(--line-1)" }}>
            <div className="col gap-1">
              <h2 className="t-h1">Hosted by {r.host}</h2>
              <p className="t-sm muted">Superhost · 3 years on Roomly · 47 stays completed</p>
            </div>
            <span className="avatar avatar-lg b3">{r.host[0]}</span>
          </div>

          {/* Room facts */}
          <div className="col gap-4">
            <h3 className="t-h2">Room facts</h3>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 12 }}>
              {[
                { i: "bed", t: "Private bedroom · twin bed", d: "Furnished, with desk + lockable closet" },
                { i: "users", t: "Shared with 3 housemates", d: "Quiet hours 10pm–7am" },
                { i: "key", t: "Personal key + smart lock", d: "Coded entry, no shared keys" },
                { i: "cash", t: "$685/month · utilities included", d: "WiFi, heat, water" },
                { i: "shield", t: "Background-checked household", d: "All adults run through Persona" },
                { i: "calendar", t: "Min stay 30 days", d: "Month-to-month after first 30" },
              ].map(f => (
                <div key={f.t} className="row gap-3" style={{ padding: "12px 0" }}>
                  <Icon name={f.i} style={{ color: "var(--ink-2)", marginTop: 2 }} />
                  <div className="col">
                    <span className="t-h3">{f.t}</span>
                    <span className="t-sm muted">{f.d}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <hr className="divider" />

          {/* About */}
          <div className="col gap-3">
            <h3 className="t-h2">About this room</h3>
            <p className="t-body" style={{ color: "var(--ink-1)" }}>
              Spacious upstairs bedroom in a calm, three-bedroom craftsman two blocks from the West Oakland BART. Shared kitchen and a sunny back porch.
              We're a quiet household — two students and one part-time nurse — and we're looking for a respectful new housemate who values clean common spaces.
            </p>
            <p className="t-body" style={{ color: "var(--ink-1)" }}>
              We accept HUD-VASH, Section 8, and Emergency Housing Vouchers. Case workers welcome on tours. The room is fully furnished — twin bed, desk, lamp, dresser — and ready to move in.
            </p>
          </div>

          <hr className="divider" />

          {/* Programs accepted */}
          <div className="col gap-3">
            <h3 className="t-h2">Programs accepted</h3>
            <div className="row gap-2" style={{ flexWrap: "wrap" }}>
              {["HUD-VASH", "Section 8 (HCV)", "EHV", "Veterans Affairs", "Bay Area Outreach", "Roots Recovery"].map(p => (
                <span key={p} className="chip chip-static"><Icon name="check" className="i i-sm" style={{ color: "var(--accent)" }} /> {p}</span>
              ))}
            </div>
          </div>

          <hr className="divider" />

          {/* Reviews */}
          <div className="col gap-4">
            <div className="row spread">
              <h3 className="t-h2">Reviews · {r.reviews}</h3>
              <div className="row gap-2 t-sm">
                <Icon name="star" className="i i-sm" style={{ color: "var(--accent)" }} />
                <span className="t-mono">{r.rating}</span>
                <span className="muted">average</span>
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 24 }}>
              {[
                { n: "Carla T.", d: "March 2026", t: "Dana was so kind. She picked me up from the bus station and showed me the room before I even committed. The house is quiet and I sleep through the night for the first time in a year." },
                { n: "Reggie W.", d: "February 2026", t: "Fair price, clean room, and Dana checks in once a week to make sure things are good. My case worker had no trouble with paperwork." },
                { n: "Yasmin H.", d: "January 2026", t: "I felt safe here. The lock works, the lights work, the shower is hot. That's a lot." },
                { n: "Mike R.", d: "December 2025", t: "First stable address I've had in three years. Just signed a six-month extension." },
              ].map((rev, i) => (
                <div key={i} className="col gap-3">
                  <div className="row gap-3">
                    <span className={`avatar b${(i % 4) + 1}`}>{rev.n[0]}</span>
                    <div className="col">
                      <span className="t-h3">{rev.n}</span>
                      <span className="t-sm muted">{rev.d}</span>
                    </div>
                  </div>
                  <p className="t-sm" style={{ color: "var(--ink-1)" }}>"{rev.t}"</p>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Reservation card */}
        <aside style={{ position: "sticky", top: 92, alignSelf: "start" }}>
          <div className="card card-pad" style={{ padding: 24, boxShadow: "var(--elev-1)" }}>
            <div className="row spread" style={{ marginBottom: 16 }}>
              <div className="col">
                <span className="t-mono" style={{ fontSize: 26 }}>${r.price}<span className="muted t-sm" style={{ fontFamily: "var(--font-sans)" }}> / month</span></span>
                <span className="t-sm muted">utilities included</span>
              </div>
              <span className="badge badge-success"><span className="dot live" /> Available</span>
            </div>

            <div className="col gap-2" style={{ marginBottom: 12 }}>
              <div className="row gap-2" style={{ padding: "12px 14px", background: "var(--bg-2)", borderRadius: 8, boxShadow: "0 0 0 1px var(--line-1) inset" }}>
                <Icon name="calendar" className="i i-sm" style={{ color: "var(--ink-2)" }} />
                <div className="col" style={{ flex: 1 }}>
                  <span className="t-mono-xs muted">Move in</span>
                  <span className="t-sm">May 8, 2026</span>
                </div>
                <span className="v-divider" style={{ height: 28 }} />
                <div className="col">
                  <span className="t-mono-xs muted">Length</span>
                  <span className="t-sm">6 months</span>
                </div>
              </div>
              <div className="row gap-2" style={{ padding: "12px 14px", background: "var(--bg-2)", borderRadius: 8, boxShadow: "0 0 0 1px var(--line-1) inset" }}>
                <Icon name="cash" className="i i-sm" style={{ color: "var(--ink-2)" }} />
                <div className="col" style={{ flex: 1 }}>
                  <span className="t-mono-xs muted">Paying with</span>
                  <span className="t-sm">HUD-VASH voucher</span>
                </div>
                <Icon name="chevDown" className="i i-sm muted" />
              </div>
            </div>

            <button className="btn btn-primary btn-lg" style={{ width: "100%", marginBottom: 8 }}>Request to apply</button>
            <button className="btn btn-outline" style={{ width: "100%" }}><Icon name="msg" className="i i-sm" /> Message host</button>

            <hr className="divider" style={{ margin: "20px 0" }} />

            <div className="col gap-2 t-sm">
              <div className="row spread"><span className="muted">Monthly rent</span><span className="t-mono">$685.00</span></div>
              <div className="row spread"><span className="muted">Utilities</span><span className="t-mono">included</span></div>
              <div className="row spread"><span className="muted">Roomly service fee</span><span className="t-mono">$0.00</span></div>
              <div className="row spread" style={{ marginTop: 8, paddingTop: 12, borderTop: "1px solid var(--line-1)" }}>
                <span className="t-h3">Total to host</span>
                <span className="t-mono" style={{ fontSize: 16 }}>$685 / mo</span>
              </div>
            </div>
            <p className="t-sm muted-soft" style={{ marginTop: 12, textAlign: "center" }}>You won't be charged yet.</p>
          </div>
          <p className="t-sm muted" style={{ textAlign: "center", marginTop: 16 }}>
            <Icon name="flag" className="i i-sm" style={{ verticalAlign: "middle", marginRight: 4 }} />
            Concerned about this listing? <a style={{ color: "var(--accent)", cursor: "pointer" }}>Tell us</a>
          </p>
        </aside>
      </div>
    </main>
  );
};

window.PageSearch = PageSearch;
window.PageListing = PageListing;
