(function () {
/* Comparable KVI baskets and saved advisory strategy. All values come from /pricing/market. */
const {useState: pmState, useEffect: pmEffect} = React;
const pmMoney = c => c == null ? "—" : "$" + (c / 100).toLocaleString("en-AU",{minimumFractionDigits:2,maximumFractionDigits:2});
const pmPct = p => p == null ? "—" : (p > 0 ? "+" : "") + p.toFixed(1) + "%";
function PricingMarket() {
  const {setScreen, setScreenState} = window.useOffice();
  const [data,setData] = pmState(null);
  const [selected,setSelected] = pmState(null);
  const [loading,setLoading] = pmState(true);
  const [saving,setSaving] = pmState(false);
  const [error,setError] = pmState(null);
  const [notice,setNotice] = pmState(null);
  const [reload,setReload] = pmState(0);
  const [showAdd,setShowAdd] = pmState(false);
  pmEffect(()=>{const refresh=()=>setReload(k=>k+1);window.addEventListener("office-pricing-refresh",refresh);return()=>window.removeEventListener("office-pricing-refresh",refresh);},[]);
  const [showAll,setShowAll] = pmState(false);
  const [search,setSearch] = pmState("");
  const [page,setPage] = pmState(0);
  pmEffect(()=>setPage(0),[search]);
  pmEffect(() => {
    let alive = true;
    setLoading(true); setError(null);
    window.OfficeAPI.pricingMarket(selected ? {strategy:selected} : undefined)
      .then(d => { if(alive) setData(d); })
      .catch(e => { if(alive) setError(e.message || "Couldn't load the market basket."); })
      .finally(() => { if(alive) setLoading(false); });
    return () => {alive=false;};
  },[selected,reload]);
  const preview = !!data && data.strategy.id !== data.savedStrategyId;
  const ready = !!data && !loading && (!selected || data.strategy.id === selected);
  const choose = id => {setSelected(id); setNotice(null);};
  const save = async () => {
    if(!ready || !preview || saving) return;
    setSaving(true); setError(null); setNotice(null);
    try {
      await window.OfficeAPI.savePricingStrategy({id:data.strategy.id});
      setNotice("Saved. This stance now guides advisory recommendations for this scope. Shelf prices are unchanged.");
      setSelected(null); setReload(k=>k+1);
    } catch(e) {setError(e.message || "Couldn't save this stance.");}
    finally {setSaving(false);}
  };
  const open = r => {
    setScreenState(st=>({...st,priceProductId:r.productId,priceFrom:"pricePosition",priceMethod:undefined,priceStrategy:preview ? data.strategy.id : undefined}));
    setScreen("priceDetail");
  };
  const s=data && data.summary, c=data && data.coverage;
  const rows=data ? data.rows.filter(r=>!search.trim() || [r.name,r.sku,r.brand].some(v=>(v||"").toLowerCase().includes(search.trim().toLowerCase()))) : [];
  const Kpi=window.KpiCard;
  return <div className="off-screen">
    <window.CompetitorPricingHeader>
      <button className="btn btn--ghost btn--sm" onClick={()=>setShowAdd(v=>!v)} aria-expanded={showAdd}><window.OIcon name="plus" /> Add competitor price</button>
      <button className="btn btn--secondary btn--sm" disabled={loading || saving} onClick={()=>setReload(k=>k+1)}><window.OIcon name="refresh" /> Refresh prices</button>
    </window.CompetitorPricingHeader>
    <div className="off-screen-body off-pricing-body off-pricing-market-body">
      {showAdd && <window.CompetitorCaptureForm onSaved={()=>{setShowAdd(false);setReload(k=>k+1);}} onCancel={()=>setShowAdd(false)} />}
      {error && <div className="off-pricing-note off-pricing-error" role="alert">{error}</div>}
      {notice && <div className="off-pricing-note off-pricing-success" role="status">{notice}</div>}
      {loading && <div className="off-pricing-note" role="status">{data ? "Recalculating the basket preview…" : "Loading observed prices and the comparable KVI basket…"}</div>}
      {data && <>
        <div className="off-pricing-kpis">
          <Kpi label="KVI basket vs cheapest" value={s.basketCount ? pmPct(s.gapPct) : "—"} delta={{text:s.aboveCount + " of " + s.basketCount + " comparable lines are dearer"}} />
          <Kpi label="Widest gap" value={s.widestLine ? pmPct(s.widestLine.gapPct) : "—"} delta={{text:s.widestLine ? s.widestLine.name : "No comparable lines"}} />
          <Kpi label="Basket value · you" value={s.basketCount ? pmMoney(s.ownSumCents) : "—"} delta={{text:s.basketCount + " known value items · one unit each"}} />
          <Kpi label="Cost to match cheaper prices" value={s.basketCount ? pmMoney(s.costToMatchCents) : "—"} delta={{text:"Shelf value reduction per basket · before cost floors"}} />
        </div>
        <window.PricingScopeDisclosure>
          <b>{c.comparedProducts} of {c.namedKviProducts} KVI products compared.</b> Latest usable price per retailer in the last 90 days.
          <p>{c.missingObservations || 0} without comparable observations · {c.missingOwnPrice || 0} without a shelf price · {c.missingCost || 0} without a usable cost · {c.excludedPackComparisons || 0} pack comparisons excluded · {c.excludedBasisComparisons || 0} incompatible price bases excluded.</p>
          <p>{data.scopeNote}</p>
        </window.PricingScopeDisclosure>
        <section className="off-table pc-card">
          <div className="pc-card-h">Position against each retailer</div>
          <div className="pc-card-s">KVI basket only · each comparison uses the same overlapping products</div>
          {data.retailers.length ? <div className="pc-posbars">{data.retailers.map(r=><div className="pc-posbar" key={r.id}>
            <span className="pc-posbar-l">{r.name}</span><div className="pc-posbar-t" aria-hidden="true"><span className="pc-posbar-mid"/><span className="pc-posbar-f" style={{[r.gapPct>=0?"left":"right"]:"50%",width:Math.min(50,Math.abs(r.gapPct||0)*1.1)+"%",background:r.gapPct>0?"var(--void)":"var(--paid)"}}/></div>
            <strong className={r.gapPct > 0 ? "pc-posbar-v off-pricing-up" : "pc-posbar-v off-pricing-down"}>{pmPct(r.gapPct)}</strong>
            <span className="off-pricing-small">{r.aboveCount} of {r.overlapCount} dearer</span>
          </div>)}</div> : <div className="off-pricing-empty">No retailers have comparable KVI observations yet. Add a competitor price to begin.</div>}
          <div className="pc-card-s">Above zero means your basket is dearer. {c.comparedProducts} products have comparable observations in the last 90 days.</div>
        </section>
        <section className="off-pricing-section">
          <div className="off-table off-pricing-data-card">
            <div className="off-pricing-toolbar"><h3 className="off-card-title">Line by line</h3><span className="off-pricing-small">{preview ? "Preview" : "Saved stance"} · {data.strategy.name}</span></div>

            {rows.length ? <div className="off-pricing-table-wrap"><table className="off-pricing-table off-pricing-market-table"><colgroup><col/><col style={{width:104}}/><col style={{width:150}}/><col style={{width:96}}/><col style={{width:110}}/><col style={{width:96}}/></colgroup><thead><tr><th>Product</th><th className="off-pricing-num">You</th><th>Cheapest observed</th><th className="off-pricing-num">Gap</th><th className="off-pricing-num">Recommended</th><th className="off-pricing-num">Gap then</th></tr></thead>
              <tbody>{rows.slice(page*10,(page+1)*10).map(r=><tr key={r.productId}>
                <td className="off-pricing-product"><button className="off-pricing-text-button" disabled={!ready} aria-label={"Open " + r.name} onClick={()=>open(r)}>{r.name}</button><span className="off-pricing-small">{r.sku || "No SKU"}{r.category ? " · " + r.category : ""}</span></td>
                <td className="off-pricing-num">{pmMoney(r.ownCents)}</td>
                <td>{pmMoney(r.cheapestCents)}<span className="off-pricing-small">{typeof r.cheapestRetailer === "string" ? r.cheapestRetailer : r.cheapestRetailer.name}</span></td>
                <td className={"off-pricing-num " + (r.gapPct>0 ? "off-pricing-up" : "off-pricing-down")}>{pmPct(r.gapPct)}</td>
                <td className="off-pricing-num"><b>{loading ? "…" : pmMoney(r.recommendedCents)}</b>{r.recommendedCents == null && <span className="off-pricing-small">Needs cost / evidence</span>}</td>
                <td className="off-pricing-num">{loading ? "…" : pmPct(r.gapThenPct)}</td>
              </tr>)}</tbody></table></div> : <div className="off-pricing-empty">{s.basketCount ? "No KVI lines match this filter." : "No comparable KVI basket yet. Observations must match a named KVI product and its selling unit."}</div>}
          </div>
          {rows.length > 10 && <div className="off-pricing-pagination"><span>{page*10+1}–{Math.min((page+1)*10,rows.length)} of {rows.length}</span><button className="btn btn--ghost btn--sm" disabled={!page} onClick={()=>setPage(p=>p-1)}>Previous</button><button className="btn btn--ghost btn--sm" disabled={(page+1)*10>=rows.length} onClick={()=>setPage(p=>p+1)}>Next</button></div>}
        </section>
        <section className="off-table pc-card">
          <div className="pc-card-h">Pick a stance</div><div className="pc-card-s">Preview the trade-off, then set the stance that guides recommendations.</div>
          <div className="off-pricing-strategies" role="radiogroup" aria-label="Pricing stance">{data.strategies.map(st=><button type="button" role="radio" aria-checked={(selected || data.strategy.id)===st.id} className="off-pricing-stance" data-selected={(selected || data.strategy.id)===st.id} key={st.id} disabled={saving} onClick={()=>choose(st.id)}>
            <span><strong>{st.name}</strong><span className="off-pricing-small">{st.description}</span>
              <strong className="off-pricing-preview-value">{st.preview.gpGivenUpCents == null ? "—" : pmMoney(st.preview.gpGivenUpCents)} GP given up</strong>
              <span className="off-pricing-small">Ex GST · one unit each · {st.preview.changedLines} lines move</span>
              <span className="off-pricing-small">Basket gap then {pmPct(st.preview.gapThenPct)}</span>
            </span>
          </button>)}</div>
          <div className="off-pricing-save"><span>{preview ? "Preview — this stance is not saved yet." : "Saved stance · " + data.strategy.name} Shelf prices are changed separately in Manage stock.</span><button className="btn btn--primary btn--sm" disabled={!ready || !preview || saving} onClick={save}>{saving ? "Saving…" : "Set stance"}</button></div>
        </section>
        <details className="off-pricing-observations" open={showAll} onToggle={e=>setShowAll(e.currentTarget.open)}>
          <summary>Browse all competitor observations</summary>
          <div className="off-pricing-note">Broader monitoring view, including non-KVI and older observations. These rows are separate from the 90-day comparable basket above.</div>
          {showAll && window.AllCompetitorObservations && <window.AllCompetitorObservations />}
        </details>
      </>}
    </div>
  </div>;
}
window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, {pricePosition:PricingMarket});

})();
