/* ============================================================
   Parcels — list, grid map view, cell info panel
   ============================================================ */

/* ---------- Parcels list ---------- */
function ParcelsList({ go, parcels }) {
  return (
    <div className="view">
      <section style={{ background: "var(--green-tint)", borderBottom: "1px solid var(--line-soft)" }}>
        <div className="wrap" style={{ padding: "56px 0 48px" }}>
          <span className="eyebrow">Parcele</span>
          <h1 style={{ fontSize: "clamp(34px,5vw,52px)", marginTop: 12, maxWidth: 620 }}>
            Alege o parcelă și deschide harta
          </h1>
          <p className="muted" style={{ fontSize: 18, maxWidth: 520, marginTop: 14 }}>
            Fiecare parcelă e o grilă de sloturi. Apasă pe orice celulă disponibilă ca să adopți copacul plantat acolo.
          </p>
        </div>
      </section>
      <section className="section" style={{ paddingTop: 48 }}>
        <div className="wrap">
          <div className="feat-grid">
            {parcels.map(p => {
              const pct = Math.round((p.adopted / p.total) * 100);
              return (
                <div key={p.id} className="card" style={{ overflow: "hidden", cursor: "pointer" }} onClick={() => go("parcel", { id: p.id })}>
                  <div className="imgph green" style={{ height: 150, borderRadius: 0 }}>imagine satelit · {p.place}</div>
                  <div className="col" style={{ padding: 22, gap: 14 }}>
                    <div className="row between center">
                      <h3 style={{ fontSize: 22 }}>{p.name}</h3>
                      <span className="badge"><Icon name="pin" size={12} /> {p.county}</span>
                    </div>
                    <p className="muted" style={{ fontSize: 14.5, minHeight: 42 }}>{p.desc}</p>
                    <div className="row gap16 wrapf" style={{ fontSize: 13 }}>
                      <span className="badge">{p.rows}×{p.cols} sloturi</span>
                      <span className="badge">{p.spacing} m distanță</span>
                      <span className="badge">{p.area} m²</span>
                    </div>
                    <div className="col" style={{ gap: 8, marginTop: 2 }}>
                      <div className="row between" style={{ fontSize: 13, fontWeight: 600 }}>
                        <span className="muted">{p.available} disponibili</span>
                        <span style={{ color: "var(--green)" }}>{pct}% adoptat</span>
                      </div>
                      <div style={{ height: 8, background: "var(--surface-2)", borderRadius: 10, overflow: "hidden" }}>
                        <div style={{ width: pct + "%", height: "100%", background: "var(--green)", borderRadius: 10 }}></div>
                      </div>
                    </div>
                    <button className="btn btn-soft btn-block">Deschide harta <Icon name="arrowR" size={16} /></button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>
    </div>
  );
}

/* ---------- Parcel grid map ---------- */
function ParcelView({ go, parcel, onAdopt, cart }) {
  const [selected, setSelected] = useState(null);
  const [mode, setMode] = useState("grid"); // grid | list
  const [zoom, setZoom] = useState(34);     // cell px
  const [filter, setFilter] = useState("all");

  if (!parcel) return null;
  const pct = Math.round((parcel.adopted / parcel.total) * 100);
  const cell = selected ? parcel.cells.find(c => c.id === selected) : null;

  const inCart = (id) => cart.some(c => c.cellId === id);

  const visible = parcel.cells.filter(c => filter === "all" || c.status === filter);

  return (
    <div className="view">
      {/* Sub-header */}
      <section style={{ borderBottom: "1px solid var(--line-soft)", background: "var(--surface)" }}>
        <div className="wrap" style={{ padding: "22px 0" }}>
          <button className="btn btn-ghost btn-sm" onClick={() => go("parcels")} style={{ marginBottom: 16 }}>
            <Icon name="arrowL" size={15} /> Toate parcelele
          </button>
          <div className="row between center wrapf" style={{ gap: 20 }}>
            <div className="col" style={{ gap: 8 }}>
              <h1 style={{ fontSize: "clamp(26px,3.4vw,38px)" }}>{parcel.name}</h1>
              <div className="row gap12 wrapf" style={{ fontSize: 13.5 }}>
                <span className="badge"><Icon name="pin" size={12} /> {parcel.place}</span>
                <span className="badge">{parcel.rows}×{parcel.cols} grilă</span>
                <span className="badge"><Icon name="clock" size={12} /> din {parcel.started}</span>
              </div>
            </div>
            <div className="row gap24 center">
              <div className="col" style={{ alignItems: "flex-end", gap: 4 }}>
                <span className="stat-num" style={{ fontSize: 30, color: "var(--green)" }}>{pct}%</span>
                <span className="faint" style={{ fontSize: 12.5 }}>{parcel.adopted}/{parcel.total} adoptați</span>
              </div>
              <div style={{ width: 150, height: 8, background: "var(--surface-2)", borderRadius: 10, overflow: "hidden" }} className="hide-sm">
                <div style={{ width: pct + "%", height: "100%", background: "var(--green)", borderRadius: 10 }}></div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Toolbar */}
      <div className="wrap" style={{ paddingTop: 24 }}>
        <div className="row between center wrapf" style={{ gap: 14, marginBottom: 18 }}>
          <div className="row gap8 wrapf">
            <button className={"chip" + (filter === "all" ? " chip-on" : "")} onClick={() => setFilter("all")} style={chipStyle(filter === "all")}>Toate ({parcel.total})</button>
            <button className="chip" onClick={() => setFilter("available")} style={chipStyle(filter === "available")}>
              <span className="dot" style={{ background: "var(--surface-2)", border: "1px solid var(--line)" }}></span>Disponibil ({parcel.available})</button>
            <button className="chip" onClick={() => setFilter("adopted")} style={chipStyle(filter === "adopted")}>
              <span className="dot" style={{ background: "var(--green)" }}></span>Adoptat</button>
            <button className="chip" onClick={() => setFilter("reserved")} style={chipStyle(filter === "reserved")}>
              <span className="dot" style={{ background: "var(--st-reserved)" }}></span>Rezervat</button>
          </div>
          <div className="row gap12 center">
            {mode === "grid" && (
              <div className="row gap8 center hide-sm">
                <Icon name="zoom" size={15} style={{ color: "var(--ink-faint)" }} />
                <input type="range" min="22" max="56" value={zoom} onChange={e => setZoom(+e.target.value)}
                  style={{ accentColor: "var(--green)", width: 90 }} />
              </div>
            )}
            <div className="seg">
              <button className={mode === "grid" ? "on" : ""} onClick={() => setMode("grid")}><Icon name="grid" size={15} /> Grilă</button>
              <button className={mode === "list" ? "on" : ""} onClick={() => setMode("list")}><Icon name="list" size={15} /> Listă</button>
            </div>
          </div>
        </div>
      </div>

      {/* Map + panel */}
      <div className="wrap" style={{ paddingBottom: 72 }}>
        <div className="map-layout" style={{ gridTemplateColumns: cell ? "1fr 360px" : "1fr" }}>
          <div className="card" style={{ padding: 22, overflow: "auto" }}>
            {mode === "grid" ? (
              <div className="parcel-grid" style={{ gridTemplateColumns: `repeat(${parcel.cols}, ${zoom}px)`, gap: Math.round(zoom / 6), width: "max-content", margin: "0 auto" }}>
                {parcel.cells.map(c => {
                  const dim = filter !== "all" && c.status !== filter;
                  return (
                    <button key={c.id}
                      className={`cell is-${c.status}${selected === c.id ? " sel" : ""}${inCart(c.id) ? " incart" : ""}`}
                      style={{ width: zoom, height: zoom, opacity: dim ? 0.28 : 1, transition: "opacity .2s" }}
                      title={`${c.row + 1}·${c.col + 1} — ${HELP.statusLabel(c.status)}`}
                      onClick={() => setSelected(c.id)}>
                      <span className="canopy"></span>
                      {inCart(c.id) && <span className="incart-tick"><Icon name="check" size={zoom > 30 ? 13 : 10} stroke={3} /></span>}
                    </button>
                  );
                })}
              </div>
            ) : (
              <ListView cells={visible} selected={selected} onSelect={setSelected} inCart={inCart} />
            )}
            <div className="row between center wrapf" style={{ marginTop: 20, paddingTop: 18, borderTop: "1px solid var(--line-soft)", gap: 14 }}>
              <Legend compact />
              <span className="faint" style={{ fontSize: 12.5 }}>Apasă pe o celulă pentru detalii</span>
            </div>
          </div>

          {cell && (
            <CellPanel cell={cell} parcel={parcel} close={() => setSelected(null)}
              onAdopt={onAdopt} inCart={inCart(cell.id)} go={go} />
          )}
        </div>
      </div>
    </div>
  );
}

function chipStyle(on) {
  return on ? { background: "var(--green)", color: "#f6f7f0", borderColor: "var(--green)" } : { background: "var(--surface)" };
}

/* ---------- Compact list view ---------- */
function ListView({ cells, selected, onSelect, inCart }) {
  return (
    <div className="col" style={{ gap: 2 }}>
      <div className="lv-row lv-head">
        <span>Slot</span><span>Stare</span><span>Specie</span><span>Copac</span><span>Tutore</span><span></span>
      </div>
      {cells.map(c => (
        <button key={c.id} className={"lv-row" + (selected === c.id ? " on" : "")} onClick={() => onSelect(c.id)}>
          <span className="mono" style={{ fontWeight: 600 }}>R{c.row + 1}·C{c.col + 1}</span>
          <span><span className={`pill pill-${c.status}`}><span className="dot" style={{ background: stColor(c.status) }}></span>{HELP.statusLabel(c.status)}</span></span>
          <span>{c.species.name}</span>
          <span style={{ fontWeight: 600 }}>{c.treeName || "—"}</span>
          <span className="muted">{c.donor || "—"}</span>
          <span style={{ textAlign: "right" }}>{inCart(c.id) ? <span className="pill pill-adopted">în coș</span> : <Icon name="arrowR" size={15} style={{ color: "var(--ink-faint)" }} />}</span>
        </button>
      ))}
    </div>
  );
}
function stColor(s) { return { available: "var(--ink-faint)", reserved: "var(--clay)", adopted: "var(--green)", review: "#9a958a" }[s]; }

/* ---------- Cell info panel ---------- */
function CellPanel({ cell, parcel, close, onAdopt, inCart, go }) {
  const isAvail = cell.status === "available";
  return (
    <aside className="card cell-panel" style={{ padding: 0, overflow: "hidden", alignSelf: "start", position: "sticky", top: 88 }}>
      <div className="imgph green" style={{ height: 180, borderRadius: 0, position: "relative" }}>
        {cell.photos > 0 ? `foto copac · ${cell.photos} actualizări` : "slot disponibil"}
        <button onClick={close} className="hdr-cart" style={{ position: "absolute", top: 12, right: 12, background: "var(--surface)" }}><Icon name="close" size={16} /></button>
        <span className={`pill pill-${cell.status}`} style={{ position: "absolute", left: 14, bottom: 14 }}>
          <span className="dot" style={{ background: stColor(cell.status) }}></span>{HELP.statusLabel(cell.status)}</span>
      </div>
      <div className="col" style={{ padding: 22, gap: 16 }}>
        <div className="col" style={{ gap: 4 }}>
          <span className="eyebrow">Slot R{cell.row + 1} · C{cell.col + 1}</span>
          <h3 style={{ fontSize: 24 }}>{cell.treeName || `Slot disponibil`}</h3>
          <span className="muted" style={{ fontSize: 14 }}>{cell.species.name} · <i>{cell.species.latin}</i></span>
        </div>

        <div className="col" style={{ gap: 1, background: "var(--line-soft)", borderRadius: 12, overflow: "hidden" }}>
          <PanelRow label="Parcelă" value={parcel.name} />
          {cell.treeId && <PanelRow label="ID copac" value={<span className="mono">{cell.treeId}</span>} />}
          {cell.planted && <PanelRow label="Data plantării" value={HELP.fmtDate(cell.planted)} />}
          {cell.donor && <PanelRow label={isAvail ? "Rezervat de" : "Tutore"} value={cell.donor} />}
          <PanelRow label="CO₂ estimat" value={`~${cell.species.co2} kg / an`} />
        </div>

        {isAvail ? (
          <div className="col gap12">
            <div className="row between center" style={{ padding: "2px 2px" }}>
              <span className="muted" style={{ fontSize: 14 }}>Cost adopție</span>
              <span style={{ fontFamily: "var(--font-display)", fontSize: 26, fontWeight: 600 }}>{DATA.PRICE} lei</span>
            </div>
            {inCart
              ? <button className="btn btn-soft btn-block" onClick={() => go("checkout")}><Icon name="check" size={16} /> În coș — vezi coșul</button>
              : <button className="btn btn-primary btn-block btn-lg" onClick={() => onAdopt(cell, parcel)}><Icon name="heart" size={17} /> Adoptă acest copac</button>}
            <p className="faint" style={{ fontSize: 12.5, textAlign: "center" }}>Poți dărui copacul — adaugi numele la checkout.</p>
          </div>
        ) : cell.status === "reserved" ? (
          <div className="card" style={{ background: "var(--clay-tint)", border: "1px solid var(--clay-soft)", padding: 16, fontSize: 14, color: "var(--clay-deep)" }}>
            Acest slot e rezervat și așteaptă confirmarea plății. Revino în curând sau alege altă celulă.
          </div>
        ) : (
          <div className="col gap12">
            <button className="btn btn-soft btn-block" onClick={() => go("tree", { id: cell.treeId, parcelId: parcel.id, cellId: cell.id })}>
              <Icon name="camera" size={16} /> Vezi evoluția & {cell.photos} fotografii
            </button>
            <button className="btn btn-ghost btn-block btn-sm"><Icon name="share" size={15} /> Distribuie adopția</button>
          </div>
        )}
      </div>
    </aside>
  );
}

function PanelRow({ label, value }) {
  return (
    <div className="row between center" style={{ background: "var(--surface)", padding: "11px 14px", fontSize: 14 }}>
      <span className="muted">{label}</span>
      <span style={{ fontWeight: 600, textAlign: "right" }}>{value}</span>
    </div>
  );
}

Object.assign(window, { ParcelsList, ParcelView });
