// Item detail drawer — the trust centerpiece (GET /items/{item_pk})

const detailStyles = `
  .detail-drawer {
    position: fixed; top: 0; right: 0;
    width: 620px; max-width: 96vw; height: 100vh;
    background: var(--bg);
    border-left: 1px solid var(--line);
    z-index: 92;
    display: flex; flex-direction: column;
    box-shadow: var(--shadow-pop);
    transform: none;
  }
  .detail-head {
    display: flex; align-items: center; justify-content: space-between;
    padding: 12px 18px; border-bottom: 1px solid var(--line);
    background: var(--surface-2); flex: none;
  }
  .detail-head .dh-left { display: flex; align-items: center; gap: 10px; min-width: 0; }
  .detail-head .crumb { font-family: var(--font-mono); font-size: 11px; color: var(--muted); }
  .detail-body { flex: 1; overflow-y: auto; }
  .detail-foot {
    flex: none; padding: 12px 18px; border-top: 1px solid var(--line);
    background: var(--surface-2);
    display: flex; gap: 10px; align-items: center;
  }

  /* gallery */
  .gallery { padding: 18px; display: grid; grid-template-columns: 1fr 96px; gap: 12px; }
  .gallery-main {
    aspect-ratio: 4/3;
    border-radius: var(--r);
    overflow: hidden;
    border: 1px solid var(--line);
    background: var(--bg-sunken);
  }
  .gallery-thumbs { display: flex; flex-direction: column; gap: 8px; overflow-y: auto; max-height: 348px; padding-right: 2px; }
  .gallery-thumbs .gt {
    aspect-ratio: 1;
    border-radius: var(--r-sm);
    overflow: hidden;
    border: 1px solid var(--line);
    cursor: pointer;
    opacity: 0.7;
    transition: opacity .12s;
    background: var(--bg-sunken);
  }
  .gallery-main > .thumb-img,
  .gallery-main > .thumb-ph,
  .gallery-thumbs .gt > .thumb-img,
  .gallery-thumbs .gt > .thumb-ph {
    width: 100%;
    height: 100%;
  }
  .gallery-thumbs .gt:hover, .gallery-thumbs .gt.active { opacity: 1; border-color: var(--accent); }

  .d-title { padding: 0 18px 14px; }
  .d-title h2 { margin: 0 0 8px; font-size: 18px; font-weight: 600; line-height: 1.35; color: var(--ink); }
  .d-title .d-tags { display: flex; flex-wrap: wrap; gap: 6px; }

  /* hero valuation band */
  .hero-band {
    margin: 0 18px 16px; padding: 16px;
    border: 1px solid var(--line); border-radius: var(--r-lg);
    background: var(--surface);
    display: grid; grid-template-columns: 1.2fr 1px 1fr 1fr; gap: 16px; align-items: center;
  }
  .hero-band.below { background: linear-gradient(135deg, var(--accent-tint), var(--surface) 120%); border-color: var(--accent-soft); }
  .hero-ratio { display: flex; flex-direction: column; gap: 3px; }
  .hero-ratio .hr-k { font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); font-weight: 600; }
  .hero-ratio .hr-v { font-family: var(--font-mono); font-size: 38px; font-weight: 600; line-height: 0.95; color: var(--ink); font-feature-settings: "tnum"; }
  .hero-band.below .hero-ratio .hr-v { color: var(--accent-deep); }
  .hero-ratio .hr-sub { font-size: 11px; color: var(--muted); }
  .hero-vrule { background: var(--line); width: 1px; height: 48px; }
  .hero-cell .hc-k { font-size: 9.5px; letter-spacing: 0.07em; text-transform: uppercase; color: var(--muted); font-weight: 600; }
  .hero-cell .hc-v { font-family: var(--font-mono); font-size: 17px; font-weight: 600; color: var(--ink); margin-top: 3px; font-feature-settings: "tnum"; }
  .hero-cell .hc-sub { font-size: 10px; color: var(--muted); margin-top: 1px; }

  /* section */
  .d-sect { padding: 16px 18px; border-top: 1px solid var(--line); }
  .d-sect > h4 {
    margin: 0 0 12px; font-size: 11px; font-weight: 600;
    letter-spacing: 0.1em; text-transform: uppercase; color: var(--muted);
    display: flex; align-items: center; gap: 8px;
  }
  .d-sect > h4 .badge { margin-left: auto; text-transform: none; letter-spacing: 0; }

  .kv-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 1px; background: var(--line); border: 1px solid var(--line); border-radius: var(--r); overflow: hidden; }
  .kv { background: var(--surface); padding: 9px 12px; display: flex; flex-direction: column; gap: 2px; }
  .kv .k { font-size: 10px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--muted); font-weight: 600; }
  .kv .v { font-family: var(--font-mono); font-size: 13px; color: var(--ink); font-feature-settings: "tnum"; }
  .kv .v.muted { color: var(--muted); }
  .kv .v.gold { color: var(--accent-deep); font-weight: 600; }

  /* honesty */
  .reason {
    display: flex; gap: 10px; padding: 10px 0; border-bottom: 1px dashed var(--line); align-items: flex-start;
  }
  .reason:last-child { border-bottom: 0; }
  .reason .rc-dot { width: 8px; height: 8px; border-radius: 50%; margin-top: 5px; flex: none; }
  .reason .rc-body { flex: 1; }
  .reason .rc-label { font-size: 13px; font-weight: 500; color: var(--ink); display: flex; align-items: center; gap: 8px; }
  .reason .rc-tip { font-size: 12px; color: var(--muted); line-height: 1.45; margin-top: 2px; }
  .reason .rc-cat { font-family: var(--font-mono); font-size: 9.5px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted-2); }

  .status-banner {
    display: flex; align-items: center; gap: 10px;
    padding: 11px 13px; border-radius: var(--r); margin-bottom: 12px;
    font-size: 13px; border: 1px solid;
  }
  .status-banner .sb-ic { flex: none; }
  .status-banner.priced { background: var(--live-soft); border-color: rgba(47,143,94,0.25); color: var(--live); }
  .status-banner.review { background: var(--hot-soft); border-color: rgba(194,74,44,0.25); color: var(--hot); }
  .status-banner.skipped { background: var(--bg-sunken); border-color: var(--line); color: var(--muted); }
  .status-banner b { color: var(--ink); }
  .status-banner .sb-txt { color: var(--ink-2); font-weight: 400; }

  /* weight evidence */
  .evidence { background: var(--surface); border: 1px solid var(--line); border-radius: var(--r); overflow: hidden; }
  .evidence-row { padding: 11px 13px; border-bottom: 1px solid var(--line); }
  .evidence-row:last-child { border-bottom: 0; }
  .evidence-row .er-k { font-size: 10px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); font-weight: 600; margin-bottom: 5px; display: flex; align-items: center; gap: 6px; }
  .evidence-row .er-quote {
    font-family: var(--font-mono); font-size: 12px; color: var(--ink-2);
    background: var(--bg-soft); border-left: 2px solid var(--accent); border-radius: 0 4px 4px 0;
    padding: 8px 10px; line-height: 1.5;
  }

  /* feedback form */
  .fb-form { background: var(--surface); border: 1px solid var(--line); border-radius: var(--r); padding: 14px; }
  .fb-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px; }
  .fb-stars { display: flex; gap: 4px; }
  .fb-stars .st { color: var(--line-strong); cursor: pointer; transition: color .1s; }
  .fb-stars .st.on { color: var(--accent); }

  /* related */
  .related-row { display: flex; gap: 10px; overflow-x: auto; padding-bottom: 4px; }
  .related-card {
    flex: none; width: 150px; border: 1px solid var(--line); border-radius: var(--r);
    overflow: hidden; cursor: pointer; background: var(--surface); transition: border-color .12s;
  }
  .related-card:hover { border-color: var(--line-strong); }
  .related-card .rc-thumb {
    aspect-ratio: 4/3;
    overflow: hidden;
    background: var(--bg-sunken);
  }
  .related-card .rc-thumb > .thumb-img,
  .related-card .rc-thumb > .thumb-ph {
    width: 100%;
    height: 100%;
  }
  .related-card .rc-info { padding: 8px; }
  .related-card .rc-t { font-size: 11px; color: var(--ink); line-height: 1.3; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
  .related-card .rc-r { font-family: var(--font-mono); font-size: 12px; font-weight: 600; margin-top: 4px; }

  /* anon gate */
  .anon-gate {
    background: linear-gradient(135deg, var(--accent-tint), var(--surface) 130%);
    border: 1px dashed var(--accent-soft); border-radius: var(--r);
    padding: 14px; display: flex; align-items: center; gap: 12px;
  }
  .anon-gate .ag-txt { flex: 1; }
  .anon-gate .ag-txt h5 { margin: 0 0 2px; font-size: 13px; color: var(--ink); }
  .anon-gate .ag-txt p { margin: 0; font-size: 12px; color: var(--muted); line-height: 1.4; }
`;

if (!document.getElementById("detail-styles")) {
  const s = document.createElement("style");
  s.id = "detail-styles"; s.textContent = detailStyles;
  document.head.appendChild(s);
}

const STATUS_META = {
  priced: { tone:"priced", label:"Priced", icon:<I.check size={15}/>, txt:"Successfully valued against live gold spot." },
  priced_review_required: { tone:"review", label:"Priced — review required", icon:<I.eye size={15}/>, txt:"Valued, but flagged for human review. Treat the estimate with caution." },
  skipped: { tone:"skipped", label:"Not priced", icon:<I.x size={15}/>, txt:"Could not be valued — see reasons below." },
  skipped_policy: { tone:"skipped", label:"Skipped by policy", icon:<I.x size={15}/>, txt:"Excluded from pricing by a material/authenticity policy gate." },
};

const ReasonCode = ({ code }) => {
  const rc = REASON_CODES[code]; if (!rc) return null;
  const tone = REASON_CAT_TONE[rc.category] || "neutral";
  const color = { live:"var(--live)", gold:"var(--accent)", hot:"var(--hot)", info:"var(--info)", neutral:"var(--muted-2)" }[tone];
  return (
    <div className="reason">
      <span className="rc-dot" style={{background: color}}/>
      <div className="rc-body">
        <div className="rc-label">{rc.label} <span className="rc-cat">{rc.category.replace("_"," ")}</span></div>
        <div className="rc-tip">{rc.tooltip}</div>
      </div>
    </div>
  );
};

const FeedbackForm = ({ item, signedIn, onComingSoon }) => {
  return (
    <ComingSoon
      variant="inline"
      feature="Feedback"
      detail="Ground-truth reports need accounts, so feedback is paused for the anonymous MVP."
      onAction={() => onComingSoon?.("Feedback", "Ground-truth reports need accounts, so feedback is paused for the anonymous MVP.")}
      actionLabel="Coming soon"
    />
  );
  const [rating, setRating] = React.useState(0);
  const [bought, setBought] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  if (!signedIn) {
    return (
      <div className="anon-gate">
        <I.spark size={20} style={{color:"var(--accent-deep)"}}/>
        <div className="ag-txt">
          <h5>Help train the estimates</h5>
          <p>Sign in to report the real karat, weight, and what you paid. Your feedback sharpens future valuations.</p>
        </div>
        <button className="btn accent sm">Sign in</button>
      </div>
    );
  }
  if (sent) {
    return <div className="status-banner priced" style={{marginBottom:0}}><I.check size={15} className="sb-ic"/><span className="sb-txt"><b>Thanks!</b> Your ground-truth report was recorded.</span></div>;
  }
  return (
    <div className="fb-form">
      <div className="fb-grid">
        <div><label className="lbl">Actual karat</label><input className="input mono" placeholder={item.karat ? `${item.karat}K` : "e.g. 14K"}/></div>
        <div><label className="lbl">Actual total weight</label><input className="input mono" placeholder={item.totalWeight ? `${item.totalWeight} g` : "grams"}/></div>
        <div><label className="lbl">Purchase price</label><input className="input mono" placeholder="$0.00"/></div>
        <div>
          <label className="lbl">Did you buy it?</label>
          <div className="seg" style={{width:"fit-content"}}>
            <button className={bought ? "active" : ""} onClick={() => setBought(true)}>Yes</button>
            <button className={!bought ? "active" : ""} onClick={() => setBought(false)}>No</button>
          </div>
        </div>
      </div>
      <label className="lbl">Estimate accuracy</label>
      <div className="fb-stars" style={{marginBottom:10}}>
        {[1,2,3,4,5].map(n => (
          <span key={n} className={`st ${n <= rating ? "on" : ""}`} onClick={() => setRating(n)}><I.star size={18}/></span>
        ))}
      </div>
      <textarea className="input" style={{height:54, padding:"8px 10px", resize:"none"}} placeholder="Notes (optional) — hallmark, hollowness, packaging…"/>
      <div style={{display:"flex", justifyContent:"flex-end", marginTop:10}}>
        <button className="btn accent sm" onClick={() => setSent(true)}><I.check size={13}/> Submit feedback</button>
      </div>
    </div>
  );
};

const labelFromValue = (value) => {
  if (!value) return null;
  return String(value)
    .replace(/[_-]+/g, " ")
    .replace(/\s+/g, " ")
    .trim()
    .replace(/\b\w/g, c => c.toUpperCase());
};

const conditionLabel = (value) => CONDITION_LABEL[value] || labelFromValue(value);

const DetailDrawer = ({ item, onClose, onOpen, signedIn, onSave, related, onComingSoon }) => {
  const [activeImg, setActiveImg] = React.useState(0);
  const galleryImages = React.useMemo(() => {
    if (!item) return [];
    return Array.from(new Set([item.imageUrl, ...(item.imageUrls || [])].filter(Boolean)));
  }, [item && item.id, item && item.imageUrl, item && item.imageUrls]);
  React.useEffect(() => { setActiveImg(0); }, [item && item.id]);
  if (!item) return null;
  const priced = item.meltValue != null;
  const below = item.ratio != null && item.ratio < 1.0;
  const sm = STATUS_META[item.pricingStatus] || STATUS_META.skipped;
  const purityPct = item.karat ? (KARAT_PURITY[item.karat] * 100).toFixed(2) : null;
  const activeImage = galleryImages[activeImg] || galleryImages[0] || null;

  return (
    <>
      <div className="scrim" onClick={onClose}/>
      <div className="detail-drawer" role="dialog">
        <div className="detail-head">
          <div className="dh-left">
            <button className="btn icon sm ghost" onClick={onClose}><I.chevR size={15}/></button>
            <span className="crumb">eBay #{item.itemId}</span>
            {item.tier && <Badge tone={item.tier === "steal" ? "neutral" : "gold"}>{TIER_LABEL[item.tier]}</Badge>}
            {item.coverage && <Badge tone="outline">{item.coverage}</Badge>}
          </div>
          <div style={{display:"flex", gap:8}}>
            <SaveBtn item={item} signedIn={signedIn} onSave={onSave}/>
            <button className="btn icon sm ghost" onClick={onClose}><I.x size={15}/></button>
          </div>
        </div>

        <div className="detail-body">
          {/* gallery */}
          <div className="gallery">
            <div className="gallery-main"><ThumbPh item={item} src={activeImage} alt={`${item.title} photo ${activeImg + 1}`}/></div>
            <div className="gallery-thumbs">
              {(galleryImages.length ? galleryImages : [null]).map((src, i) => (
                <div key={src || i} className={`gt ${i === activeImg ? "active" : ""}`} onClick={() => setActiveImg(i)}><ThumbPh item={item} src={src} alt={`${item.title} thumbnail ${i + 1}`}/></div>
              ))}
            </div>
          </div>

          <div className="d-title">
            <h2>{item.title}</h2>
            <div className="d-tags">
              <Badge tone="neutral">{item.itemType}</Badge>
              {item.karat && <Badge tone="gold">{item.karat}K {item.isSolidGold ? "solid" : ""}</Badge>}
              <Badge tone="neutral">{conditionLabel(item.condition)}</Badge>
              {item.authenticityGuarantee && <Badge tone="info" icon={<I.check size={9}/>}>eBay Authenticity Guarantee</Badge>}
              {item.requiresReview && <Badge tone="hot" icon={<I.eye size={9}/>}>Review required</Badge>}
            </div>
          </div>

          {/* hero valuation */}
          <div className={`hero-band ${below ? "below" : ""}`}>
            <div className="hero-ratio">
              <span className="hr-k">Price-to-melt ratio</span>
              <span className="hr-v">{item.ratio != null ? `${item.ratio.toFixed(2)}×` : "N/A"}</span>
              <span className="hr-sub">{item.ratio == null ? "Weight unknown — cannot price" : below ? "Below the value of its gold" : "Above raw melt value"}</span>
            </div>
            <div className="hero-vrule"/>
            <div className="hero-cell">
              <div className="hc-k">All-in price</div>
              <div className="hc-v">{money(item.allIn)}</div>
              <div className="hc-sub">{item.shipping ? `incl. ${moneyC(item.shipping)} ship` : "free shipping"}</div>
            </div>
            <div className="hero-cell">
              <div className="hc-k">Deal score</div>
              <div className="hc-v">{item.dealScore != null ? item.dealScore : "—"}</div>
              <div className="hc-sub">{item.dealScore != null ? "higher is better" : "not scored"}</div>
            </div>
          </div>

          {/* valuation breakdown */}
          <div className="d-sect">
            <h4>Valuation breakdown</h4>
            <div className="kv-grid">
              <div className="kv"><span className="k">Est. gold melt value</span><span className="v gold">{money(item.meltValue)}</span></div>
              <div className="kv"><span className="k">Gold spot used</span><span className="v">{moneyC(item.spotPerGram)}/g</span></div>
              <div className="kv"><span className="k">Gold weight est.</span><span className="v">{item.goldWeight != null ? `${item.goldWeight} g` : "unknown"}</span></div>
              <div className="kv"><span className="k">Total weight</span><span className="v">{item.totalWeight != null ? `${item.totalWeight} g` : "unknown"}</span></div>
              <div className="kv"><span className="k">Karat / purity</span><span className="v">{item.karat ? `${item.karat}K · ${purityPct}%` : "unknown"}</span></div>
              <div className="kv"><span className="k">Weight basis</span><span className="v">{WB_LABEL[item.weightBasis]} <span className="muted">({item.weightBasis})</span></span></div>
            </div>
          </div>

          {/* honesty panel */}
          <div className="d-sect">
            <h4>Why this verdict <Badge tone={item.overallConfidence === "high" ? "live" : item.overallConfidence === "medium" ? "gold" : "hot"}>{item.overallConfidence} confidence</Badge></h4>
            <div className={`status-banner ${sm.tone}`}>
              <span className="sb-ic">{sm.icon}</span>
              <span className="sb-txt"><b>{sm.label}.</b> {sm.txt}</span>
            </div>
            <div>
              {item.reasonCodes.map(c => <ReasonCode key={c} code={c}/>)}
            </div>
          </div>

          {/* weight evidence */}
          <div className="d-sect">
            <h4>How we estimated the weight</h4>
            <div className="evidence">
              <div className="evidence-row">
                <div className="er-k"><I.scale size={12}/> Weight basis · {item.weightBasis} {item.weightRequiresReview && <Badge tone="hot">needs review</Badge>}</div>
                <div className="er-quote">
                  {item.weightBasis === "text" && `Listing text states the metal weight directly. Confidence: ${item.weightConfidence}.`}
                  {item.weightBasis === "image" && `No stated weight — gold weight inferred from image-scale analysis of the photos. Confidence: ${item.weightConfidence}. Treat as an estimate.`}
                  {item.weightBasis === "none" && `No weight could be determined from the listing text or photos. Item cannot be priced until a weight is known.`}
                </div>
              </div>
              {item.weightBasis !== "none" && (
                <div className="evidence-row">
                  <div className="er-k"><I.tag size={12}/> Listing excerpt</div>
                  <div className="er-quote">“…{item.karat}K {item.itemType}, {item.totalWeight}g total{item.hasStones ? ", set with stones" : ", solid gold"}, ships from {item.location}…”</div>
                </div>
              )}
              {item.weightBasis === "image" && (
                <div className="evidence-row">
                  <div className="er-k"><I.spark size={12}/> Image-scale reasoning</div>
                  <div className="er-quote">Reference object (coin/ruler) detected in photo 2; chain link gauge and length used to approximate volume → mass at {item.karat}K density.</div>
                </div>
              )}
            </div>
          </div>

          {/* classification + seller */}
          <div className="d-sect">
            <h4>Classification &amp; seller</h4>
            <div className="kv-grid">
              <div className="kv"><span className="k">Item type</span><span className="v">{item.itemType}</span></div>
              <div className="kv"><span className="k">Primary metal</span><span className="v">{item.primaryMetal}</span></div>
              <div className="kv"><span className="k">Condition</span><span className="v">{conditionLabel(item.condition) || "unknown"}</span></div>
              <div className="kv"><span className="k">Coverage</span><span className="v">{item.coverage}</span></div>
              <div className="kv"><span className="k">Seller</span><span className="v">@{item.seller}</span></div>
              <div className="kv"><span className="k">Feedback</span><span className="v">{item.sellerFeedbackPercent}% · {item.sellerFeedbackScore.toLocaleString()}</span></div>
            </div>
          </div>

          {/* feedback */}
          <div className="d-sect">
            <h4>Was this accurate?</h4>
            <FeedbackForm item={item} signedIn={signedIn} onComingSoon={onComingSoon}/>
          </div>

          {/* related */}
          {related && related.length > 0 && (
            <div className="d-sect">
              <h4>Related items</h4>
              <div className="related-row">
                {related.map(r => (
                  <div key={r.id} className="related-card" onClick={() => onOpen?.(r)}>
                    <div className="rc-thumb"><ThumbPh item={r}/></div>
                    <div className="rc-info">
                      <div className="rc-t">{r.title}</div>
                      <div className="rc-r" style={{color: r.ratio != null && r.ratio < 1 ? "var(--accent-deep)" : "var(--ink-2)"}}>{r.ratio != null ? `${r.ratio.toFixed(2)}×` : "needs wt"}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        <div className="detail-foot">
          <a className="btn primary" href={item.listingUrl} target="_blank" rel="noreferrer" style={{flex:1, justifyContent:"center"}}>
            <I.ext size={14}/> Open original eBay listing
          </a>
          <button className="btn accent" onClick={(e)=>onSave?.(item, e)}>
            <I.star size={14}/> Save
          </button>
        </div>
      </div>
    </>
  );
};

Object.assign(window, { DetailDrawer, ReasonCode, STATUS_META });
