// StompGear — Step 3: Listing Preview with Inline Editing

const CONDITIONS = ["New", "Like New", "Good", "Fair"];

function PhotoGallery({ photos, onChange }) {
  const [dragIdx, setDragIdx] = React.useState(null);

  const removePhoto = id => onChange(photos.filter(p => p.id !== id));
  const addPhoto = e => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = ev => {
      const newPhoto = { id: Date.now(), url: ev.target.result, isStock: false, label: "Owner photo" };
      onChange([...photos, newPhoto]);
    };
    reader.readAsDataURL(file);
  };

  const inputRef = React.useRef(null);
  const [main, ...thumbs] = photos;

  return (
    <div>
      {/* Main photo */}
      <div style={{ position: "relative", background: "#1a1a1a", borderRadius: 0 }}>
        {main ? (
          <>
            <img src={main.url} alt="Main" style={{ width: "100%", height: 280, objectFit: "cover", display: "block" }} onError={e => { e.target.style.background = "#e5e7eb"; e.target.style.height = "280px"; }} />
            {main.isStock && (
              <div style={{ position: "absolute", top: 10, left: 10, padding: "3px 8px", background: "rgba(0,0,0,0.65)", borderRadius: 4, color: "#fff", fontSize: 10, fontWeight: 600, fontFamily: "'Inter', sans-serif", letterSpacing: "0.05em" }}>STOCK PHOTO</div>
            )}
            <button onClick={() => removePhoto(main.id)} style={{ position: "absolute", top: 10, right: 10, width: 28, height: 28, borderRadius: "50%", background: "rgba(0,0,0,0.6)", border: "none", color: "#fff", fontSize: 15, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>×</button>
          </>
        ) : (
          <div style={{ height: 280, display: "flex", alignItems: "center", justifyContent: "center", background: "#f3f4f6", flexDirection: "column", gap: 8 }}>
            <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#d1d5db" strokeWidth="1.5">
              <path d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" /><circle cx="12" cy="13" r="3" />
            </svg>
            <span style={{ fontSize: 12, color: "#9ca3af", fontFamily: "'Inter', sans-serif" }}>No main photo</span>
          </div>
        )}
      </div>

      {/* Thumbnail row */}
      <div style={{ display: "flex", gap: 3, padding: "3px 0 0", background: "#111", overflowX: "auto" }}>
        {thumbs.map(p => (
          <div key={p.id} style={{ position: "relative", flexShrink: 0 }}>
            <img src={p.url} alt="" style={{ width: 90, height: 64, objectFit: "cover", display: "block", opacity: p.isStock ? 0.7 : 1 }} onError={e => { e.target.style.background = "#333"; }} />
            {p.isStock && <div style={{ position: "absolute", bottom: 2, left: 2, fontSize: 8, color: "rgba(255,255,255,0.7)", fontFamily: "'Inter', sans-serif", fontWeight: 600, letterSpacing: "0.05em" }}>STOCK</div>}
            <button onClick={() => removePhoto(p.id)} style={{ position: "absolute", top: 3, right: 3, width: 18, height: 18, borderRadius: "50%", background: "rgba(0,0,0,0.7)", border: "none", color: "#fff", fontSize: 11, cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", padding: 0 }}>×</button>
          </div>
        ))}

        {/* Add photo */}
        <div onClick={() => inputRef.current?.click()} style={{ width: 90, height: 64, border: "2px dashed rgba(255,255,255,0.2)", borderRadius: 2, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", cursor: "pointer", flexShrink: 0, gap: 3 }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="2"><path d="M12 5v14M5 12h14" /></svg>
          <span style={{ fontSize: 9, color: "rgba(255,255,255,0.4)", fontFamily: "'Inter', sans-serif", fontWeight: 600, letterSpacing: "0.04em" }}>ADD PHOTO</span>
        </div>
        <input ref={inputRef} type="file" accept="image/*" style={{ display: "none" }} onChange={addPhoto} />
      </div>

      {/* Required photo notice */}
      {!photos.some(p => !p.isStock) && (
        <div style={{ background: "#fff7ed", padding: "8px 14px", display: "flex", alignItems: "center", gap: 8 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#ea580c" strokeWidth="2"><circle cx="12" cy="12" r="10" /><path d="M12 8v4m0 4h.01" /></svg>
          <span style={{ fontSize: 12, color: "#9a3412", fontFamily: "'Inter', sans-serif", fontWeight: 500 }}>
            Add at least one real photo of your item before publishing — it builds trust with renters
          </span>
        </div>
      )}
    </div>
  );
}

function PricingCard({ listing, update, isMobile }) {
  const whyTooltip = `Suggested at ~${Math.round((listing.dailyRate / listing.retailValue) * 100)}% of retail value per day, based on comparable listings on StompGear.`;
  const [showWhy, setShowWhy] = React.useState(false);

  return (
    <div style={{ background: "#fff", borderRadius: 4, boxShadow: "0px 14px 24px 0px rgba(0,0,0,0.18)", padding: "20px 20px 18px", border: "1px solid #f0f0f0" }}>
      {/* Price header */}
      <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginBottom: 4 }}>
        <span style={{ fontFamily: "'Inter', sans-serif", fontWeight: 700, fontSize: 26, color: "#015672" }}>
          <EditableNumber value={listing.dailyRate} prefix="$" onChange={v => update("dailyRate", v)} />
        </span>
        <span style={{ fontSize: 14, color: "#9ca3af", fontFamily: "'Inter', sans-serif" }}> / day</span>
        <ConfidenceFlag level={listing.confidence?.dailyRate} />
        <span style={{ position: "relative", marginLeft: 2 }}>
          <button onClick={() => setShowWhy(!showWhy)} style={{ background: "none", border: "none", cursor: "pointer", fontSize: 11, color: "#6b7280", fontFamily: "'Inter', sans-serif", padding: "2px 0", textDecoration: "underline dotted" }}>Why?</button>
          {showWhy && (
            <div style={{ position: "absolute", bottom: "120%", right: 0, zIndex: 200, background: "#1f2937", color: "#f9fafb", padding: "10px 14px", borderRadius: 6, fontSize: 12, fontFamily: "'Inter', sans-serif", width: 220, lineHeight: 1.6, boxShadow: "0 4px 16px rgba(0,0,0,0.35)" }}>
              {whyTooltip}
              <button onClick={() => setShowWhy(false)} style={{ display: "block", marginTop: 6, background: "none", border: "none", color: "#9ca3af", fontSize: 11, cursor: "pointer", padding: 0, fontFamily: "'Inter', sans-serif" }}>Dismiss</button>
            </div>
          )}
        </span>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 6, margin: "12px 0 16px", fontSize: 13, fontFamily: "'Inter', sans-serif", color: "#374151" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span style={{ color: "#6b7280" }}>Weekly rate</span>
          <span style={{ fontWeight: 500 }}><EditableNumber value={listing.weeklyRate} prefix="$" onChange={v => update("weeklyRate", v)} /></span>
        </div>
        {listing.monthlyRate > 0 && (
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <span style={{ color: "#6b7280" }}>Monthly rate</span>
            <span style={{ fontWeight: 500 }}><EditableNumber value={listing.monthlyRate} prefix="$" onChange={v => update("monthlyRate", v)} /></span>
          </div>
        )}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span style={{ color: "#6b7280" }}>Min. booking</span>
          <span style={{ fontWeight: 500, color: "#374151" }}>{listing.minBookingLength || "1 Day"}</span>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span style={{ color: "#6b7280" }}>Security deposit <ConfidenceFlag level={listing.confidence?.deposit} /></span>
          <span style={{ fontWeight: 500 }}><EditableNumber value={listing.deposit} prefix="$" onChange={v => update("deposit", v)} /></span>
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span style={{ color: "#6b7280" }}>Replacement value</span>
          <span style={{ fontWeight: 500, color: "#9ca3af" }}><EditableNumber value={listing.retailValue} prefix="$" onChange={v => update("retailValue", v)} /></span>
        </div>
      </div>

      <div style={{ height: 1, background: "#f0f0f0", margin: "12px 0" }} />
      <div style={{ fontSize: 11, color: "#6b7280", fontFamily: "'Inter', sans-serif", marginBottom: 12, lineHeight: 1.6 }}>
        Deposit protects you if gear is returned damaged. <span style={{ color: "#015672", cursor: "pointer", textDecoration: "underline" }}>Learn more</span>
      </div>

      <div style={{ padding: "8px 12px", background: "#f7f8f9", borderRadius: 4, fontSize: 12, color: "#374151", fontFamily: "'Inter', sans-serif", textAlign: "center" }}>
        <svg style={{ verticalAlign: "middle", marginRight: 4 }} width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" /><circle cx="12" cy="11" r="3" /></svg>
        Pickup · {listing.pickupAddress || listing.location}
      </div>
    </div>
  );
}

function Step3({ listing, setListing, onBack, viewMode }) {
  const update = (key, value) => setListing(p => ({ ...p, [key]: value }));
  const [saved, setSaved] = React.useState(false);
  const [publishAttempted, setPublishAttempted] = React.useState(false);
  const [showAdvanced, setShowAdvanced] = React.useState(false);
  const [published, setPublished] = React.useState(false);

  const hasRealPhoto = listing.photos.some(p => !p.isStock);
  const hasCondition = !!listing.condition;
  const hasRate = listing.dailyRate > 0;
  const hasTitle = !!(listing.title && listing.title.trim());
  const hasDesc = !!(listing.description && listing.description.trim());
  const canPublish = hasRealPhoto && hasCondition && hasRate && hasTitle && hasDesc;

  const requirements = [
    { label: "Real photo added", done: hasRealPhoto },
    { label: "Condition confirmed", done: hasCondition },
    { label: "Daily rate set", done: hasRate },
    { label: "Title & description", done: hasTitle && hasDesc }
  ];

  React.useEffect(() => {
    const t = setTimeout(() => setSaved(true), 1200);
    return () => clearTimeout(t);
  }, [listing]);

  React.useEffect(() => { setSaved(false); }, [listing]);

  const isMobile = viewMode === "mobile" || window.innerWidth < 768;

  if (published) {
    return (
      <div style={{ minHeight: "100vh", background: "#F7F8F9", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: 32 }}>
        <div style={{ width: 64, height: 64, borderRadius: "50%", background: "#016a34", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 20 }}>
          <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5"><path d="M20 6L9 17l-5-5" /></svg>
        </div>
        <h2 style={{ fontFamily: "'Poppins', sans-serif", fontWeight: 700, fontSize: 24, color: "#111827", marginBottom: 8, textAlign: "center" }}>Your listing is live!</h2>
        <p style={{ fontSize: 14, color: "#6b7280", fontFamily: "'Inter', sans-serif", textAlign: "center", lineHeight: 1.65, maxWidth: 320, marginBottom: 24 }}>
          {listing.title} is now visible on StompGear. Renters in your area can find and book it.
        </p>
        <button onClick={() => setPublished(false)} style={{ padding: "12px 24px", background: "#015672", color: "#fff", border: "none", borderRadius: 4, fontSize: 13, fontWeight: 700, letterSpacing: 1, textTransform: "uppercase", fontFamily: "'Inter', sans-serif", cursor: "pointer" }}>
          View Listing
        </button>
        <button onClick={onBack} style={{ marginTop: 10, background: "none", border: "none", color: "#015672", fontSize: 13, cursor: "pointer", fontFamily: "'Inter', sans-serif", textDecoration: "underline" }}>
          List another item
        </button>
      </div>
    );
  }

  const mainContent = (
    <div style={{ maxWidth: isMobile ? "none" : 720, flex: 1 }}>
      {/* Photo gallery */}
      <PhotoGallery photos={listing.photos} onChange={v => update("photos", v)} />

      {/* Listing header */}
      <div style={{ padding: "16px 16px 0" }}>
        {/* Breadcrumb */}
        <div style={{ fontSize: 11, color: "#9ca3af", fontFamily: "'Inter', sans-serif", marginBottom: 8, display: "flex", gap: 4, alignItems: "center" }}>
          <span style={{ color: "#015672", cursor: "pointer" }}>Kimberley</span>
          <span>›</span>
          <span style={{ color: "#015672", cursor: "pointer" }}>{listing.category}</span>
          <span>|</span>
          <span style={{ color: "#015672", cursor: "pointer" }}>{listing.subcategory}</span>
          <span>|</span>
          <span>{listing.rentalType || listing.subcategory}</span>
        </div>

        {/* Title */}
        <div style={{ marginBottom: 8 }}>
          <EditableText
            value={listing.title}
            onChange={v => update("title", v)}
            tag="h1"
            style={{ fontFamily: "'Montserrat', sans-serif", fontWeight: 700, fontSize: 20, color: "#111827", lineHeight: 1.3, margin: 0, display: "block" }}
            placeholder="Add a title for your listing…"
          />
          <ConfidenceFlag level={listing.confidence?.title} />
        </div>

        {/* Meta row */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 12, color: "#6b7280", fontFamily: "'Inter', sans-serif", marginBottom: 14, flexWrap: "wrap" }}>
          <span>★★★★★ <span style={{ color: "#9ca3af" }}>New listing</span></span>
          <span>·</span>
          <span><EditableText value={listing.size} onChange={v => update("size", v)} style={{ fontSize: 12, color: "#374151", fontWeight: 500 }} placeholder="Add size…" /></span>
          <span>·</span>
          <span style={{ display: "flex", alignItems: "center", gap: 3 }}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" /><circle cx="12" cy="11" r="3" /></svg>
            <EditableText value={listing.location} onChange={v => update("location", v)} style={{ fontSize: 12, color: "#374151" }} />
          </span>
        </div>

        {/* Mobile pricing (only on narrow view) */}
        {isMobile && (
          <div style={{ marginBottom: 20 }}>
            <PricingCard listing={listing} update={update} isMobile />
          </div>
        )}
      </div>

      {/* Content sections */}
      <div style={{ padding: "0 16px" }}>

        {/* Condition — always required */}
        <div style={{ marginBottom: 20, padding: "14px 16px", background: hasCondition ? "#f0fff6" : "#fff7ed", borderRadius: 8, border: `1px solid ${hasCondition ? "#bbf7d0" : "#fed7aa"}` }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
            <span style={{ fontSize: 13, fontWeight: 600, fontFamily: "'Inter', sans-serif", color: "#111827" }}>Condition</span>
            <ConfidenceFlag level={hasCondition ? "high" : "required"} />
          </div>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {CONDITIONS.map(c => (
              <button key={c} onClick={() => update("condition", c)} style={{ padding: "7px 14px", borderRadius: 4, border: `1.5px solid ${listing.condition === c ? "#015672" : "#e5e7eb"}`, background: listing.condition === c ? "#015672" : "#fff", color: listing.condition === c ? "#fff" : "#374151", fontSize: 13, fontFamily: "'Inter', sans-serif", fontWeight: listing.condition === c ? 600 : 400, cursor: "pointer", transition: "all 0.12s" }}>
                {c}
              </button>
            ))}
          </div>
          {!hasCondition && (
            <p style={{ margin: "8px 0 0", fontSize: 11, color: "#9a3412", fontFamily: "'Inter', sans-serif" }}>Required before publishing — only you know the real condition</p>
          )}
        </div>

        {/* Specs */}
        <div style={{ marginBottom: 20 }}>
          <div style={{ fontSize: 13, fontWeight: 600, fontFamily: "'Poppins', sans-serif", color: "#111827", marginBottom: 10 }}>About This Item</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
            {[
              { label: "Brand", key: "brand", conf: null },
              { label: "Model", key: "model", conf: null },
              { label: "Year", key: "year", conf: listing.confidence?.year },
              { label: "Size", key: "size", conf: null },
              { label: "Frame Type", key: "frameType", conf: null },
              { label: "Wheel Size", key: "wheelSize", conf: null },
              { label: "Brake Type", key: "brakeType", conf: null },
              { label: "Rental Type", key: "rentalType", conf: null }
            ].map(f => (
              <div key={f.key} style={{ padding: "10px 12px", background: "#f9fafb", borderRadius: 6, border: "1px solid #f3f4f6" }}>
                <div style={{ fontSize: 10, fontWeight: 600, color: "#9ca3af", fontFamily: "'Inter', sans-serif", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 3, display: "flex", alignItems: "center", gap: 4 }}>
                  {f.label} <ConfidenceFlag level={f.conf} />
                </div>
                <EditableText
                  value={listing[f.key] ? String(listing[f.key]) : ""}
                  onChange={v => update(f.key, v)}
                  style={{ fontSize: 13, fontWeight: 500, color: "#111827", fontFamily: "'Inter', sans-serif" }}
                  placeholder={`Add ${f.label.toLowerCase()}…`}
                />
              </div>
            ))}
          </div>
        </div>

        {/* Description */}
        <div style={{ marginBottom: 20 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
            <div style={{ fontSize: 13, fontWeight: 600, fontFamily: "'Poppins', sans-serif", color: "#111827" }}>Description</div>
            <ConfidenceFlag level={listing.confidence?.description} />
          </div>
          <div style={{ padding: "4px 0", fontSize: 13, color: "#374151", fontFamily: "'Inter', sans-serif", lineHeight: 1.7 }}>
            {listing.description ? listing.description.split("\n\n").map((para, i) => (
              <div key={i} style={{ marginBottom: i < listing.description.split("\n\n").length - 1 ? 12 : 0 }}>
                <EditableText value={para} onChange={v => { const parts = listing.description.split("\n\n"); parts[i] = v; update("description", parts.join("\n\n")); }} style={{ fontSize: 13, color: "#374151", fontFamily: "'Inter', sans-serif", lineHeight: 1.7, display: "block" }} multiline placeholder="Add a description paragraph…" />
              </div>
            )) : (
              <EditableText value="" onChange={v => update("description", v)} multiline placeholder="Describe your gear for renters…" style={{ fontSize: 13, color: "#374151", fontFamily: "'Inter', sans-serif", lineHeight: 1.7, display: "block" }} />
            )}
          </div>
        </div>

        {/* Accessories */}
        <div style={{ marginBottom: 20 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 10 }}>
            <div style={{ fontSize: 13, fontWeight: 600, fontFamily: "'Poppins', sans-serif", color: "#111827" }}>What's Included</div>
            <ConfidenceFlag level={listing.confidence?.accessories} />
          </div>
          <AccessoriesEditor items={listing.accessories} onChange={v => update("accessories", v)} />
        </div>

        {/* Rules */}
        <div style={{ marginBottom: 20, padding: "14px 16px", background: "#f7f8f9", borderRadius: 8, border: "1px solid #e5e7eb" }}>
          <div style={{ fontSize: 13, fontWeight: 600, fontFamily: "'Poppins', sans-serif", color: "#111827", marginBottom: 8 }}>Rules & Requirements</div>
          <EditableText value={listing.rules} onChange={v => update("rules", v)} multiline style={{ fontSize: 13, color: "#374151", fontFamily: "'Inter', sans-serif", lineHeight: 1.65, display: "block" }} placeholder="Add rules for renters (e.g. PFD required, experience level…)" />
        </div>

        {/* Logistics */}
        <div style={{ marginBottom: 20, padding: "14px 16px", background: "#fff", borderRadius: 8, border: "1px solid #e5e7eb" }}>
          <div style={{ fontSize: 13, fontWeight: 600, fontFamily: "'Poppins', sans-serif", color: "#111827", marginBottom: 12 }}>Logistics</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10, fontSize: 13, fontFamily: "'Inter', sans-serif" }}>
            <div style={{ display: "flex", gap: 8, alignItems: "flex-start" }}>
              <svg style={{ flexShrink: 0, marginTop: 2 }} width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#015672" strokeWidth="2"><path d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" /><circle cx="12" cy="11" r="3" /></svg>
              <div>
                <div style={{ fontSize: 10, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "#9ca3af", marginBottom: 2 }}>Pickup</div>
                <EditableText value={listing.pickupAddress} onChange={v => update("pickupAddress", v)} style={{ fontSize: 13, color: "#374151", fontWeight: 500 }} placeholder="Enter pickup address…" />
              </div>
            </div>
            <div style={{ display: "flex", gap: 8, alignItems: "flex-start" }}>
              <svg style={{ flexShrink: 0, marginTop: 2 }} width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#6b7280" strokeWidth="2"><path d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" /><circle cx="12" cy="11" r="3" /></svg>
              <div>
                <div style={{ fontSize: 10, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "#9ca3af", marginBottom: 2 }}>Drop-off</div>
                <EditableText value={listing.dropoffAddress} onChange={v => update("dropoffAddress", v)} style={{ fontSize: 13, color: "#374151", fontWeight: 500 }} placeholder="Same as pickup unless specified…" />
              </div>
            </div>
            {listing.vehicleType && (
              <div style={{ display: "flex", gap: 8, alignItems: "flex-start" }}>
                <svg style={{ flexShrink: 0, marginTop: 2 }} width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#6b7280" strokeWidth="2"><path d="M5 17H3a2 2 0 01-2-2V5a2 2 0 012-2h11a2 2 0 012 2v3m-4 12h8a2 2 0 002-2v-5a2 2 0 00-2-2h-8a2 2 0 00-2 2v5a2 2 0 002 2z" /></svg>
                <div>
                  <div style={{ fontSize: 10, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "#9ca3af", marginBottom: 2 }}>Vehicle needed</div>
                  <span style={{ fontSize: 13, color: "#374151" }}>{listing.vehicleType}</span>
                </div>
              </div>
            )}
            {listing.pickupNotes && (
              <div style={{ marginTop: 4, padding: "8px 10px", background: "#f7f8f9", borderRadius: 6, fontSize: 12, color: "#374151", lineHeight: 1.6 }}>
                <EditableText value={listing.pickupNotes} onChange={v => update("pickupNotes", v)} multiline style={{ fontSize: 12, color: "#374151", lineHeight: 1.6, display: "block" }} placeholder="Add pickup/drop-off notes…" />
              </div>
            )}
          </div>
        </div>

        {/* Delivery Add-ons */}
        {listing.deliveryAddons && listing.deliveryAddons.length > 0 && (
          <div style={{ marginBottom: 20, padding: "14px 16px", background: "#fff", borderRadius: 8, border: "1px solid #e5e7eb" }}>
            <div style={{ fontSize: 13, fontWeight: 600, fontFamily: "'Poppins', sans-serif", color: "#111827", marginBottom: 10 }}>Delivery & Add-ons</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {listing.deliveryAddons.map((addon, i) => (
                <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 13, fontFamily: "'Inter', sans-serif", padding: "6px 0", borderBottom: i < listing.deliveryAddons.length - 1 ? "1px solid #f3f4f6" : "none" }}>
                  <span style={{ color: "#374151" }}>{addon.title}</span>
                  <span style={{ color: "#6b7280" }}>${addon.price} · {addon.applied}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Availability */}
        {listing.availability && listing.availability.length > 0 && (
          <div style={{ marginBottom: 20, padding: "14px 16px", background: "#fff", borderRadius: 8, border: "1px solid #e5e7eb" }}>
            <div style={{ fontSize: 13, fontWeight: 600, fontFamily: "'Poppins', sans-serif", color: "#111827", marginBottom: 10 }}>General Hours of Availability</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
              {listing.availability.map((a, i) => (
                <div key={i} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "7px 0", borderBottom: i < listing.availability.length - 1 ? "1px solid #f7f8f9" : "none", fontSize: 13, fontFamily: "'Inter', sans-serif" }}>
                  <span style={{ color: "#374151", fontWeight: 500, minWidth: 90 }}>{a.day}</span>
                  <span style={{ display: "flex", alignItems: "center", gap: 6, color: "#6b7280" }}>
                    <span style={{ width: 7, height: 7, borderRadius: "50%", background: "#22c55e", display: "inline-block", flexShrink: 0 }}></span>
                    {a.hours}
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Owner section */}
        <div style={{ marginBottom: 20, padding: "14px 16px", background: "#fff", borderRadius: 8, border: "1px solid #e5e7eb" }}>
          <div style={{ fontSize: 13, fontWeight: 600, fontFamily: "'Poppins', sans-serif", color: "#111827", marginBottom: 12 }}>About the listing author</div>
          <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
            <div style={{ width: 48, height: 48, borderRadius: "50%", background: "#015672", display: "flex", alignItems: "center", justifyContent: "center", color: "#fff", fontSize: 17, fontWeight: 700, fontFamily: "'Montserrat', sans-serif", flexShrink: 0 }}>
              {listing.ownerName[0]}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: "#111827", fontFamily: "'Inter', sans-serif", marginBottom: 2 }}>Hello, I'm {listing.ownerName}.</div>
              <div style={{ fontSize: 12, color: "#6b7280", fontFamily: "'Inter', sans-serif", lineHeight: 1.65, marginBottom: 8 }}>
                {listing.ownerBio || "When my family isn't out skiing, biking, or exploring the backcountry, we're happy to rent out our own gear so others can enjoy it too. We believe great gear should be shared."}
                {" "}<span style={{ color: "#015672", cursor: "pointer", textDecoration: "underline" }}>more</span>
              </div>
              <div style={{ display: "flex", gap: 10 }}>
                <span style={{ fontSize: 12, color: "#015672", cursor: "pointer", textDecoration: "underline", fontFamily: "'Inter', sans-serif" }}>View profile</span>
                <span style={{ fontSize: 12, color: "#6b7280", fontFamily: "'Inter', sans-serif" }}>·</span>
                <span style={{ fontSize: 12, color: "#015672", cursor: "pointer", textDecoration: "underline", fontFamily: "'Inter', sans-serif" }}>Contact</span>
              </div>
            </div>
          </div>
        </div>

        {/* Advanced section */}
        <div style={{ marginBottom: 28 }}>
          <button onClick={() => setShowAdvanced(!showAdvanced)} style={{ background: "none", border: "none", cursor: "pointer", display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "#6b7280", fontFamily: "'Inter', sans-serif", padding: "0 0 10px" }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d={showAdvanced ? "M6 9l6 6 6-6" : "M9 18l6-6-6-6"} /></svg>
            Advanced options (tags, SEO, custom availability)
          </button>
          {showAdvanced && (
            <div style={{ padding: "14px 16px", background: "#f9fafb", borderRadius: 8, border: "1px solid #e5e7eb", fontSize: 12, color: "#6b7280", fontFamily: "'Inter', sans-serif", lineHeight: 1.7 }}>
              <div style={{ marginBottom: 8 }}>
                <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "#9ca3af", marginBottom: 4 }}>Search tags</div>
                <div style={{ fontSize: 12, color: "#374151" }}>mountain bike rental, trail bike, full suspension, Trek, Kimberley trails, Bootleg Gap, Kootenay cycling</div>
              </div>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", color: "#9ca3af", marginBottom: 4 }}>Availability</div>
                <div>Defaults to all dates available. Block dates after publishing from your listing manager.</div>
              </div>
            </div>
          )}
        </div>

      </div>
    </div>
  );

  const generated = listing._aiGenerated !== false;

  return (
    <div style={{ minHeight: "100vh", background: "#F7F8F9", display: "flex", flexDirection: "column" }}>

      {/* Sticky publish bar */}
      <div style={{ background: "#fff", borderBottom: "1px solid #e5e7eb", position: "sticky", top: 0, zIndex: 100, boxShadow: "0 1px 4px rgba(0,0,0,0.06)" }}>
        <div style={{ maxWidth: 1100, margin: "0 auto", padding: "0 16px", height: 60, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <StompLogo size={20} />
            <div style={{ display: "flex", flexDirection: "column" }}>
              <span style={{ fontSize: 11, fontWeight: 700, color: "#9ca3af", fontFamily: "'Inter', sans-serif", letterSpacing: "0.05em", textTransform: "uppercase", lineHeight: 1 }}>Preview</span>
              <span style={{ fontSize: 12, color: saved ? "#16a34a" : "#9ca3af", fontFamily: "'Inter', sans-serif", lineHeight: 1.4, marginTop: 1, transition: "color 0.3s" }}>
                {saved ? "✓ Draft saved" : "Saving…"}
              </span>
            </div>
          </div>

          {/* Requirements checklist */}
          <div style={{ display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap", justifyContent: "center" }}>
            {requirements.map(r => (
              <div key={r.label} style={{ display: "flex", alignItems: "center", gap: 3, fontSize: 10, fontFamily: "'Inter', sans-serif", color: r.done ? "#15803d" : "#9ca3af", fontWeight: 500 }}>
                <div style={{ width: 14, height: 14, borderRadius: "50%", background: r.done ? "#16a34a" : "#e5e7eb", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  {r.done && <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3"><path d="M20 6L9 17l-5-5" /></svg>}
                </div>
                <span style={{ display: "none" }}>{r.label}</span>
              </div>
            ))}
            <span style={{ fontSize: 10, color: canPublish ? "#15803d" : "#9ca3af", fontFamily: "'Inter', sans-serif", marginLeft: 2 }}>
              {requirements.filter(r => r.done).length}/{requirements.length} ready
            </span>
          </div>

          <div style={{ display: "flex", gap: 8, alignItems: "center", flexShrink: 0 }}>
            <button onClick={onBack} style={{ padding: "0 14px", height: 36, background: "#fff", border: "1px solid #e5e7eb", borderRadius: 4, fontSize: 12, fontWeight: 600, color: "#374151", cursor: "pointer", fontFamily: "'Inter', sans-serif" }}>
              ← Back
            </button>
            <button style={{ padding: "0 14px", height: 36, background: "#fff", border: "1px solid #e5e7eb", borderRadius: 4, fontSize: 12, fontWeight: 600, color: "#374151", cursor: "pointer", fontFamily: "'Inter', sans-serif", whiteSpace: "nowrap" }} onClick={() => setSaved(true)}>
              Save Draft
            </button>
            <button
              onClick={() => { if (!canPublish) { setPublishAttempted(true); } else { setPublished(true); } }}
              style={{ padding: "0 18px", height: 36, background: canPublish ? "#015672" : "#d1d5db", color: canPublish ? "#fff" : "#9ca3af", border: "none", borderRadius: 4, fontSize: 12, fontWeight: 700, letterSpacing: "0.5px", textTransform: "uppercase", cursor: canPublish ? "pointer" : "not-allowed", fontFamily: "'Inter', sans-serif", transition: "background 0.15s", whiteSpace: "nowrap" }}
              onMouseEnter={e => canPublish && (e.currentTarget.style.background = "#92BECD")}
              onMouseLeave={e => canPublish && (e.currentTarget.style.background = "#015672")}
              title={canPublish ? "Publish listing" : "Complete the required fields to publish"}
            >
              Publish Listing
            </button>
          </div>
        </div>
      </div>

      {/* AI attribution banner */}
      {generated && (
        <div style={{ background: "#f0f9ff", borderBottom: "1px solid #bae6fd", padding: "8px 16px", display: "flex", alignItems: "center", gap: 8, maxWidth: 1100, margin: "0 auto", width: "100%", boxSizing: "border-box" }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#0284c7" strokeWidth="2"><path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" /></svg>
          <span style={{ fontSize: 12, color: "#0369a1", fontFamily: "'Inter', sans-serif" }}>
            We filled this in based on what you shared. Everything is editable — click any field to update it.
            <span style={{ marginLeft: 6, opacity: 0.6 }}>Fields marked <span style={{ background: "#fef9c3", border: "1px solid #fde047", padding: "1px 5px", borderRadius: 6, fontSize: 10, color: "#854d0e", fontWeight: 700 }}>⚑ Review</span> need your attention.</span>
          </span>
        </div>
      )}

      {/* Publish warning */}
      {publishAttempted && !canPublish && (
        <div style={{ background: "#fff7ed", borderBottom: "1px solid #fed7aa", padding: "8px 16px", display: "flex", alignItems: "center", gap: 8 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#ea580c" strokeWidth="2"><circle cx="12" cy="12" r="10" /><path d="M12 8v4m0 4h.01" /></svg>
          <span style={{ fontSize: 12, color: "#9a3412", fontFamily: "'Inter', sans-serif" }}>
            Before publishing: {!hasRealPhoto && "add a real photo of your item · "}{!hasCondition && "select condition · "}{!hasRate && "set a daily rate · "}{(!hasTitle || !hasDesc) && "complete title & description"}
          </span>
        </div>
      )}

      {/* Main layout */}
      <div style={{ maxWidth: 1100, margin: "0 auto", width: "100%", boxSizing: "border-box", display: isMobile ? "block" : "grid", gridTemplateColumns: isMobile ? "none" : "1fr 340px", gap: 24, padding: isMobile ? 0 : "24px 24px 40px", alignItems: "start" }}>
        {mainContent}
        {!isMobile && (
          <div style={{ position: "sticky", top: 76 }}>
            <PricingCard listing={listing} update={update} />
            <div style={{ marginTop: 12, fontSize: 11, color: "#9ca3af", fontFamily: "'Inter', sans-serif", textAlign: "center", lineHeight: 1.6 }}>
              Renters see this panel when they visit your listing. Pricing is always editable after publishing.
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function AccessoriesEditor({ items, onChange }) {
  const [adding, setAdding] = React.useState(false);
  const [newItem, setNewItem] = React.useState("");
  const inputRef = React.useRef(null);
  React.useEffect(() => { if (adding && inputRef.current) inputRef.current.focus(); }, [adding]);

  const addItem = () => {
    if (newItem.trim()) { onChange([...items, newItem.trim()]); }
    setNewItem("");
    setAdding(false);
  };

  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 6, alignItems: "center" }}>
      {items.map((item, i) => (
        <div key={i} style={{ display: "flex", alignItems: "center", gap: 5, padding: "5px 10px", background: "#f0f9ff", border: "1px solid #bae6fd", borderRadius: 20, fontSize: 12, fontFamily: "'Inter', sans-serif", color: "#0369a1", fontWeight: 500 }}>
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M20 6L9 17l-5-5" /></svg>
          {item}
          <button onClick={() => onChange(items.filter((_, j) => j !== i))} style={{ background: "none", border: "none", cursor: "pointer", color: "#93c5fd", fontSize: 13, padding: "0 0 0 2px", lineHeight: 1, fontFamily: "sans-serif" }}>×</button>
        </div>
      ))}
      {adding ? (
        <input ref={inputRef} value={newItem} onChange={e => setNewItem(e.target.value)} onBlur={addItem} onKeyDown={e => { if (e.key === "Enter") addItem(); if (e.key === "Escape") { setAdding(false); setNewItem(""); } }} placeholder="Add item…" style={{ height: 30, padding: "0 10px", border: "1.5px solid #015672", borderRadius: 20, fontSize: 12, fontFamily: "'Inter', sans-serif", outline: "none", width: 120 }} />
      ) : (
        <button onClick={() => setAdding(true)} style={{ display: "flex", alignItems: "center", gap: 4, padding: "5px 10px", background: "none", border: "1.5px dashed #d1d5db", borderRadius: 20, fontSize: 12, fontFamily: "'Inter', sans-serif", color: "#6b7280", cursor: "pointer", fontWeight: 500 }}>
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M12 5v14M5 12h14" /></svg>
          Add item
        </button>
      )}
    </div>
  );
}

Object.assign(window, { Step3 });
