PageSourceSearch

https://restaurant-app-production.web.app/assets/Pricing-Og5_f7tE.js

js restaurant-app-production.web.app collected 2026-10-03 12:35:46 UTC 123,542 bytes, 1 lines download raw bytes

1import{r as mr}from"./rolldown-runtime-b3L32Ng1.js";import{a as pr}from"./app-DWbpOmbp.js";import{Cn as st,Ct as xr,F as gr,Lt as Le,S as br,Sn as hr,Xt as Bt,bn as it,cn as nt,fn as fr,h as he,kn as we,nr as vr,qt as Fe,rn as Kt,u as Vt,xn as Ue}from"./module-B8BOkXXh.js";import{i as yr}from"./inventoryPricing-BG1OXYxN.js";import{t as Wt}from"./productMixNormalizer-BPpq6jtf.js";import{r as Nr,u as jr}from"./recipeSalesBindings-DuBGC6Dx.js";import{Ai as Qe,ar as Sr,fr as qt,gr as zr,ir as Cr,ki as Pr,mr as Ir,nr as wr,or as T,rr as Mr,rt as ft,tr as kr}from"./main-BpGFkDZX.js";import{t as Rr}from"./useFoodCostFoundationSources-4e3elcfR.js";import{n as Gt}from"./reportQueryFailure-CGhGe18S.js";import{t as vt}from"./productMixStoreResolver-BD9CNERD.js";var w=mr(vr(),1),yt=1440*60*1e3,pe=(e,t=0)=>{const s=Number(e);return Number.isFinite(s)?s:t},Nt=e=>String(e||"").trim().toLowerCase().replace(/\s+/g," "),_r=(e={})=>{const t=pe(e.unitPrice??e.menuPrice??e.avgPrice,0);return t>0?t:null},Er=({productMixDocs:e=[],windowDays:t=90,asOf:s=null,resolveName:i=null,isExcluded:a=null}={})=>{const n=Wt(Array.isArray(e)?e:[]),o=Array.isArray(n)?n:[],l=s==null?null:typeof s=="number"?s:Date.parse(s),u=l!=null&&Number.isFinite(l)&&t>0?l-t*yt:null,p=o.filter(c=>{if(u==null)return!0;const m=Date.parse(c.businessDate);return Number.isFinite(m)?m>=u&&(l==null||m<=l):!1}),x=new Map,d=new Set,g=new Map;p.forEach(c=>{if(a&&a(c))return;const m=i?i(c):{name:c.itemName,resolved:!0},f=String(m?.name||c.itemName||"").trim(),h=String(c.posItemId||c.sku||"").trim().toLowerCase()||Nt(f)||Nt(c.itemName);if(!h)return;const P=String(c.store||"").trim();if(P){d.add(P);const C=String(c.businessDate||"").slice(0,10);if(/^\d{4}-\d{2}-\d{2}$/.test(C)){const R=g.get(P)||new Set;R.add(C),g.set(P,R)}}const I=x.get(h)||{itemKey:h,itemName:f||c.itemName,rawName:c.itemName,category:String(c.category||"").trim(),subcategory:String(c.subcategory||"").trim(),nameResolved:m?.resolved!==!1,recipeId:String(m?.recipeId||"").trim(),chainNet:0,chainQty:0,chainPriceTotal:0,chainPriceQty:0,byStore:new Map};!I.itemName&&f&&(I.itemName=f),!I.category&&c.category&&(I.category=String(c.category||"").trim()),!I.subcategory&&c.subcategory&&(I.subcategory=String(c.subcategory||"").trim()),!I.recipeId&&m?.recipeId&&(I.recipeId=String(m.recipeId||"").trim()),I.chainNet+=pe(c.netSales),I.chainQty+=pe(c.quantitySold);const M=pe(c.quantitySold),v=_r(c),j=M>0?M:v!=null?1:0;v!=null&&j>0&&(I.chainPriceTotal+=v*j,I.chainPriceQty+=j);const S=I.byStore.get(P)||{net:0,qty:0,priceTotal:0,priceQty:0,latestPriceDate:"",latestPriceTotal:0,latestPriceQty:0};if(S.net+=pe(c.netSales),S.qty+=M,v!=null&&j>0){S.priceTotal+=v*j,S.priceQty+=j;const C=String(c.businessDate||"").slice(0,10);C>S.latestPriceDate?(S.latestPriceDate=C,S.latestPriceTotal=v*j,S.latestPriceQty=j):C===S.latestPriceDate&&(S.latestPriceTotal+=v*j,S.latestPriceQty+=j)}I.byStore.set(P,S),x.set(h,I)});const z=Object.fromEntries([...d].map(c=>{const m=[...g.get(c)||[]].sort(),f=m.length?Date.parse(m[0]):NaN,h=m.length?Date.parse(m[m.length-1]):NaN,P=Number.isFinite(f)&&Number.isFinite(h)?Math.max(Math.floor((h-f)/yt)+1,1):0,I=P>0?Math.max(P/7,1):1;return[c,{firstBusinessDate:m[0]||null,lastBusinessDate:m[m.length-1]||null,observedBusinessDays:m.length,calendarDays:P,reportingWeeks:I,reportingCoveragePct:P>0?Math.min(m.length/P,1):0}]})),b=[...x.values()].map(c=>{const m=Object.fromEntries([...c.byStore.entries()].map(([I,M])=>{const v=M.latestPriceQty>0?M.latestPriceTotal/M.latestPriceQty:null;return[I,{avgPrice:v??(M.priceQty>0?M.priceTotal/M.priceQty:M.qty>0?M.net/M.qty:null),currentPriceDate:M.latestPriceDate||null,realizedUnitRevenue:M.qty>0?M.net/M.qty:null,qty:M.qty,net:M.net,reportingWeeks:z[I]?.reportingWeeks||1,reportingCoveragePct:z[I]?.reportingCoveragePct||0}]})),f=Object.values(m).filter(I=>I.avgPrice>0),h=f.reduce((I,M)=>I+Math.max(M.qty,1),0),P=h>0?f.reduce((I,M)=>I+M.avgPrice*Math.max(M.qty,1),0)/h:null;return{itemKey:c.itemKey,itemName:c.itemName,rawName:c.rawName,category:c.category,subcategory:c.subcategory,nameResolved:c.nameResolved,recipeId:c.recipeId,chainAvgPrice:P??(c.chainPriceQty>0?c.chainPriceTotal/c.chainPriceQty:c.chainQty>0?c.chainNet/c.chainQty:null),chainQty:c.chainQty,byStore:m}}
1),y=b.reduce((c,m)=>c+pe(m.chainQty),0);return{items:b,stores:[...d].filter(Boolean).sort(),totalChainQty:y,windowDays:t,rowCount:p.length,storeCoverage:z}},Ar=e=>String(e||"").trim().toLowerCase().replace(/\s+/g," "),Tr=Object.freeze({burbank:Object.freeze({medianIncome:90724,population:107337}),"simi valley":Object.freeze({medianIncome:113233,population:126356}),"santa clarita":Object.freeze({medianIncome:109440,population:228673}),"porter ranch":Object.freeze({medianIncome:152945,population:30353}),glendale:Object.freeze({medianIncome:73539,population:196543}),pasadena:Object.freeze({medianIncome:96963,population:138699}),"thousand oaks":Object.freeze({medianIncome:127e3,population:126813}),valencia:Object.freeze({medianIncome:120284,population:67e3})}),Dr=e=>String(e||"").replace(/[^0-9]/g,"").slice(0,5),Or=({stores:e=[],table:t=Tr,storeZip:s={},zipTable:i={}}={})=>{const a=p=>{const x=Dr(s[p]),d=x&&i[x];if(d&&Number(d.medianIncome)>0)return{demo:d,source:"census"};const g=t[Ar(p)];return g&&Number(g.medianIncome)>0?{demo:g,source:"seed"}:{demo:null,source:null}},n=(Array.isArray(e)?e:[]).map(p=>({store:p,...a(p)})),o=n.filter(p=>p.demo).map(p=>Number(p.demo.medianIncome)),l=o.length?o.reduce((p,x)=>p+x,0)/o.length:0,u={};return n.forEach(p=>{p.demo&&l>0?u[p.store]={available:!0,source:p.source,medianIncome:Number(p.demo.medianIncome),population:Number(p.demo.population)||null,incomeIndex:Number(p.demo.medianIncome)/l}:u[p.store]={available:!1,source:null,medianIncome:null,population:null,incomeIndex:1,flag:"demographic_unavailable"}}),{byStore:u,chainMeanIncome:l,availableCount:o.length}},at=(e,t=0)=>{const s=Number(e);return Number.isFinite(s)?s:t},Ht=(e,t)=>{const s=at(e,0),i=at(t,0);return s<=0||i<=0?0:s/i},X=(e,t={})=>{let s=at(e,0);if(s<=0)return 0;const i=t.rounding||"none";if(i==="quarter"?s=Math.round(s*4)/4:i==="half"?s=Math.round(s*2)/2:i==="whole"&&(s=Math.round(s)),t.forbidNineEndings){const a=Math.round((s-Math.floor(s))*100);(a===99||a===95)&&(s=Math.ceil(s))}return Number(s.toFixed(2))},ee=e=>String(e||"").trim(),ke=e=>ee(e).toLowerCase(),B=(e,t=null)=>{const s=Number(e);return Number.isFinite(s)?s:t},Re=Object.freeze({SOURCE_PENDING:"source_pending",AVAILABLE:"available"}),jt=Object.freeze({PRICE_LEVEL_FREE:"$",PRICE_LEVEL_INEXPENSIVE:"$",PRICE_LEVEL_MODERATE:"$$",PRICE_LEVEL_EXPENSIVE:"$$$",PRICE_LEVEL_VERY_EXPENSIVE:"$$$$"}),ot=Object.freeze(["$","$$","$$$","$$$$"]),$r=Object.freeze({google_places:"Google Maps",google_places_aggregate:"Google Maps",places_aggregate:"Google Maps",google:"Google Maps",places:"Google Maps"}),Ie=()=>({status:Re.SOURCE_PENDING,label:"Source pending",density:null,rating:null,priceTier:null,helper:"Nearby Google Maps data is updating automatically. Menu item prices are not used.",source:{provider:null,providerLabel:"Source pending",providers:[],fetchedAt:null,fetchedLabel:"",radiusMiles:null,radiusLabel:"",priceTierOnly:!0,yelpEnriched:!1},metrics:{competitorCount:0,avgPriceLevel:null,priceSampleCount:0,priceCoveragePct:0,avgRating:null,highRatedCount:0},legal:{nonBinding:!0,exactMenuPricesUsed:!1}}),Ze=e=>$r[ke(e).replace(/[\s-]+/g,"_")]||ee(e)||"Competitive source",Qt=e=>{if(!e)return null;if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e?.toDate=="function"){const s=e.toDate();return s instanceof Date&&!Number.isNaN(s.getTime())?s:null}if(typeof e=="object"&&Number.isFinite(Number(e.seconds))){const s=new Date(Number(e.seconds)*1e3);return Number.isNaN(s.getTime())?null:s}const t=new Date(e);return Number.isNaN(t.getTime())?null:t},Lr=e=>{const t=Qt(e);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):""},Fr=(e={})=>B(e.radiusMiles)??B(e.radius)??B(e.searchRadiusMiles)??B(e.density?.radiusMiles),Zt=e=>{const t=B(e);return t>0?Number.isInteger(t)?String(t):t.toFixed(1).replace(/\.0$/u,""):""},gt=e=>{if(e==null)return null;if(typeof e=="number"){const a=Math.max(1,Math.min(4,Math.round(e)));return"$".repeat(a)}const t=ee(e);if(!t)return null;if(/^\${1,4}$/.test(t))return t;const s=t.toUpperCase();if(jt[s])return jt[s];const i=s.match(/\b([1-4])\b/u)?.[1];return i?"$".repeat(Number(i)):null},Ur=e=>{const t=gt(e);return t?t.length:null},Ce=(e,t,s)=>{Array.isArray(t)&&t.forEach(i=>
1{if(!i||typeof i!="object")return;const a=ke(i.provider||s).replace(/[\s-]+/g,"_");if(a==="yelp"||a==="yelp_fusion")return;const n=ke(i.businessStatus||i.status);n==="closed_permanently"||n==="permanently_closed"||e.push({provider:ee(i.provider||s||"google_places"),rating:B(i.rating),reviewCount:B(i.userRatingCount??i.reviewCount??i.review_count??i.reviews),priceTier:gt(i.priceTier??i.priceLevel??i.priceRange??i.price)})})},Br=(e={})=>{const t=[];return Ce(t,e.competitors,e.provider),Ce(t,e.places,e.provider||"google_places"),Ce(t,e.googlePlaces,"google_places"),Ce(t,e.results,e.provider),Ce(t,e.businesses,e.provider),t},Kr=({count:e,radiusMiles:t})=>{if(!(e>0))return null;const s=Zt(t);return s?`${e} within ${s} mi`:`${e} nearby competitors`},Vr=({snapshot:e,records:t})=>{const s=B(e.rating?.highRatedCount??e.ratingPressure?.highRatedCount),i=B(e.rating?.threshold??e.ratingPressure?.threshold,4.5),a=B(e.rating?.reviewCountThreshold??e.ratingPressure?.reviewCountThreshold,250),n=s??t.filter(l=>l.rating>=i&&(l.reviewCount==null||l.reviewCount>=a)).length;if(n>0)return a>0?`High pressure: ${n} at ${i}+`:`High pressure: ${n} at ${i}+`;const o=t.map(l=>l.rating).filter(l=>l>0);return o.length?`Avg ${(o.reduce((l,u)=>l+u,0)/o.length).toFixed(1)} across peers`:e.rating?.summary||e.ratingPressure?.summary||null},Yt=({snapshot:e,records:t})=>{const s={$:0,$$:0,$$$:0,$$$$:0},i=e.priceTierCounts||e.priceTier?.counts||{};return Object.entries(i).forEach(([a,n])=>{const o=gt(a);o&&s[o]!=null&&(s[o]+=Math.max(B(n,0),0))}),t.forEach(a=>{a.priceTier&&s[a.priceTier]!=null&&(s[a.priceTier]+=1)}),s},Wr=({snapshot:e,records:t,competitorCount:s})=>{const i=Yt({snapshot:e,records:t}),a=ot.reduce((d,g)=>d+(i[g]||0),0),n=a>0?ot.reduce((d,g)=>d+Ur(g)*(i[g]||0),0)/a:null,o=t.map(d=>d.rating).filter(d=>d>0),l=o.length?o.reduce((d,g)=>d+g,0)/o.length:null,u=B(e.rating?.threshold??e.ratingPressure?.threshold,4.5),p=B(e.rating?.reviewCountThreshold??e.ratingPressure?.reviewCountThreshold,250),x=B(e.rating?.highRatedCount??e.ratingPressure?.highRatedCount)??t.filter(d=>d.rating>=u&&(d.reviewCount==null||d.reviewCount>=p)).length;return{competitorCount:s,avgPriceLevel:n==null?null:Number(n.toFixed(4)),priceSampleCount:a,priceCoveragePct:s>0?Number(Math.min(a/s,1).toFixed(4)):0,avgRating:l==null?null:Number(l.toFixed(4)),highRatedCount:x}},qr=({snapshot:e,records:t})=>{const s=e.priceTier?.summary||e.priceTierSummary;if(s)return ee(s);const i=Yt({snapshot:e,records:t}),a=ot.map(l=>[l,i[l]||0]).filter(([,l])=>l>0);if(!a.length)return null;const[n]=a.sort((l,u)=>u[1]-l[1])[0],o=(i.$$$||0)+(i.$$$$||0);return o>0?`Mostly ${n} · ${o} premium ${o===1?"peer":"peers"}`:`Mostly ${n}`},Gr=({snapshot:e,records:t})=>{const s=ee(e.provider||"google_places"),i=new Set;i.add(Ze(s)),t.forEach(n=>{const o=Ze(n.provider);o&&i.add(o)});const a=[...i].filter(Boolean);return{provider:s,providerLabel:a[0]||Ze(s),providers:a,yelpEnriched:!1}},Xt=e=>e.sourceFetchedAt||e.fetchedAt||e.updatedAt||e.createdAt||null,Jt=(e=null)=>{if(!e||typeof e!="object")return Ie();const t=ke(e.provider).replace(/[\s-]+/g,"_");if(t==="yelp"||t==="yelp_fusion"||e.status===Re.SOURCE_PENDING||e.sourcePending===!0)return Ie();const s=Br(e),i=Fr(e),a=B(e.competitorCount??e.density?.count,s.length)||0;if(!(a>0)&&!e.density?.summary&&!e.rating?.summary&&!e.priceTier?.summary)return Ie();const n=Xt(e),o=Lr(n),l=Gr({snapshot:e,records:s}),u=Wr({snapshot:e,records:s,competitorCount:a}),p=e.density?.summary||Kr({count:a,radiusMiles:i}),x=Vr({snapshot:e,records:s}),d=qr({snapshot:e,records:s}),g=i>0?`${Zt(i)} mi radius`:"",z=o?`${l.providerLabel} · ${o}`:l.providerLabel;return{status:Re.AVAILABLE,label:z,density:p,rating:x,priceTier:d,helper:"Menu item prices are not used. This context informs a non-binding suggestion only.",source:{provider:l.provider,providerLabel:l.providerLabel,providers:l.providers,fetchedAt:n,fetchedLabel:o,radiusMiles:i,radiusLabel:g,priceTierOnly:!0,yelpEnriched:l.yelpEnriched,competitorCount:a},metrics:u,legal:{nonBinding:!0,exactMenuPricesUsed:!1}}},Hr=(e=null)=>{if(e&&typeof e=="object"&&(e.source||e.legal)&&(e.density!=null||e.rating!=null||e.priceTier!=null)){const s=Ie();return{status:e.status||Re.AVAILABLE,label:e.label||"Competitive context",density:e.density??null,rating:e.rating??null,priceTier:e.priceTier??null,helper:e.helper||"Menu item prices are not used. This context informs a non-binding suggestion only.",source:{...s.source,...e.source||{},priceTierOnly:!0},metrics:{...s.metrics,...e.metrics||{}},legal:{nonBinding:!0,...e.legal||{},exactMenuPricesUsed:!1}}}const t=Jt(e);return t.status===Re.AVAILABLE||!e||typeof e!="object"?t:{...t,status:e.status||t.status,label:e.label||t.label,density:e.density??t.density,rating:e.rating??t.rating,priceTier:e.priceTier??t.priceTier,helper:e.helper||t.helper}},Qr=({snapshots:e=[]}={})=>{const t={};return(Array.isArray(e)?e:[]).map(s=>({snapshot:s,date:Qt(Xt(s))?.getTime()||0}
1)).sort((s,i)=>i.date-s.date).forEach(({snapshot:s})=>{if(!s||typeof s!="object")return;const i=ee(s.store||s.storeName);if(!i)return;const a=Jt(s);t[i]==null&&(t[i]=a);const n=ee(s.itemKey||s.itemName||s.menuItemKey);n&&(t[`${i}__${n}`]=a);const o=ke(n);o&&o!==n&&(t[`${i}__${o}`]=a)}),{byLookup:t}},be=Object.freeze({TRUSTED:"trusted",PROVISIONAL:"provisional",PENDING:"pending"}),Zr=new Set(["pack_normalized","pack-normalized","invoice_pack_normalized","invoice-pack-normalized","normalized","trusted","ready"]),re=e=>String(e||"").trim(),ae=e=>re(e).toLowerCase().replace(/\s+/g," "),J=(e,t=0)=>{const s=Number(e);return Number.isFinite(s)?s:t},Yr=(e={})=>re(e?.id||e?.recipeId),lt=e=>ae(e),$e=(e="pending_invoice_data")=>({status:be.PENDING,trusted:!1,showNumeric:!1,cost:null,displayValue:"Pending",label:"Pending",helper:"estimate · pending real invoice data",reason:e}),St=({cost:e=null,reason:t="not_invoice_pack_normalized",recipeName:s=""}={})=>({status:be.PROVISIONAL,trusted:!1,showNumeric:!1,cost:J(e,0)>0?J(e,0):null,displayValue:"Pending",label:"Estimate pending",helper:"estimate · pending real invoice data",reason:t,recipeName:re(s)}),Xr=({cost:e=null,recipeName:t=""}={})=>({status:be.TRUSTED,trusted:!0,showNumeric:!0,cost:J(e,0),displayValue:`$${J(e,0).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`,label:"Trusted",helper:"invoice-sourced · pack-normalized · no ingredient gaps",reason:"invoice_pack_normalized_no_gaps",recipeName:re(t)}),er=(e=[])=>e.map(re).filter(Boolean),Jr=(e={})=>er([e.sourceType,e.priceSource,e.sourceLabel,e.source,e.d1473?.sourceType,e.d1473?.priceSource,e.trust?.sourceType,e.priceTrust?.sourceType]).map(t=>t.toLowerCase()).some(t=>t.includes("invoice")||t.includes("ap")),es=(e={})=>e.packNormalized===!0||e.packNormalizedPrice===!0||e.normalizedFromPack===!0||e.unitNormalization?.packNormalized===!0||e.normalization?.packNormalized===!0||e.d1473?.packNormalized===!0||e.d1473?.packNormalizedPrice===!0||e.trust?.packNormalized===!0||e.priceTrust?.packNormalized===!0?!0:er([e.packNormalizationStatus,e.normalizationStatus,e.priceTrustStatus,e.trustStatus,e.d1473?.status,e.d1473?.priceTrustStatus,e.trust?.status,e.priceTrust?.status]).map(t=>t.toLowerCase().replace(/\s+/g,"_")).some(t=>Zr.has(t)),ts=(e={})=>Jr(e)&&es(e),rs=(e=[])=>{const t=new Map;
1return(Array.isArray(e)?e:[]).forEach(s=>{const i=ae(s?.item),a=ae(s?.unit);if(!i||!a)return;const n=`${i}|${a}`,o=t.get(n)||[];o.push(s),t.set(n,o)}),{byItemUnit:t}},ss=(e=[])=>{const t=new Map,s=new Map;return(Array.isArray(e)?e:[]).forEach(i=>{const a=re(i?.priceKey);if(a){const l=t.get(a)||[];l.push(i),t.set(a,l)}const n=ae(i?.catalogItem||i?.itemName),o=ae(i?.catalogUnit||i?.unit);if(n&&o){const l=`${n}|${o}`,u=s.get(l)||[];u.push(i),s.set(l,u)}}),{byPriceKey:t,byItemUnit:s}},is=({line:e={},catalogIndex:t,historyIndex:s})=>{const i=ae(e?.item||e?.matchedItem||e?.itemName),a=ae(e?.unit||e?.matchedUnit);if(!i||!a)return[];const n=[];return(t.byItemUnit.get(`${i}|${a}`)||[]).forEach(o=>{const l=yr(o);n.push(...s.byPriceKey.get(l)||[])}),n.push(...s.byItemUnit.get(`${i}|${a}`)||[]),n.filter(ts)},ns=({row:e={},catalog:t=[],pricingContext:s={}}={})=>{const i=e?.marginSnapshot||{},a=i.costSnapshot||{},n=re(i.recipeName||e?.recipe?.name),o=J(i.recipeCost??i.estimatedCostPerServing,0);if(!e?.recipe)return $e("missing_recipe");if(i.ready!==!0||J(i.unmatchedCount,0)>0||J(i.ambiguousCount,0)>0||J(i.conversionWarningCount,0)>0)return $e("ingredient_gaps");if(!(o>0))return $e("missing_cost");const l=Array.isArray(a.resolvedIngredientLines)?a.resolvedIngredientLines:[];if(!l.length)return St({cost:o,reason:"missing_resolved_lines",recipeName:n});const u=rs(t),p=ss(s.historyRecords);return l.every(x=>is({line:x,catalogIndex:u,historyIndex:p}).length>0)?Xr({cost:o,recipeName:n}):St({cost:o,reason:"not_invoice_pack_normalized",recipeName:n})},as=({foundation:e={}}={})=>{const t=Array.isArray(e.rows)?e.rows:[],s={},i={};return t.forEach(a=>{const n=ns({row:a,catalog:e.catalog,pricingContext:e.pricingContext}),o=Yr(a?.recipe),l=lt(a?.marginSnapshot?.recipeName||a?.recipe?.name);o&&(s[o]=n),l&&(i[l]=n)}),{byRecipeId:s,byItemKey:i,counts:{total:t.length,trusted:Object.values(s).filter(a=>a.status===be.TRUSTED).length,provisional:Object.values(s).filter(a=>a.status===be.PROVISIONAL).length,pending:Object.values(s).filter(a=>a.status===be.PENDING).length}}},os=({recipeId:e="",itemKey:t="",itemName:s="",foodCostByRecipeId:i={},foodCostByItemKey:a={}}={})=>i[re(e)]||a[lt(t)]||a[lt(s)]||$e(e?"food_cost_not_loaded":"missing_recipe_link"),tr=Object.freeze([0,5,10]),ct=e=>{const t=Number(e);return Number.isFinite(t)?t:null},Me=e=>{const t=ct(e);return t!=null&&t>0?t:null},dt=(e,t,s)=>Math.min(Math.max(e,t),s),U=e=>e==null?null:Number(Number(e).toFixed(2)),ie=e=>e==null?null:Number(Number(e).toFixed(6)),ls=.5,cs=1.05,ds=({currentPrice:e,realizedUnitRevenue:t}={})=>{const s=Me(e),i=Me(t);if(s==null||i==null)return{rate:1,realizedUnitRevenue:s,source:"menu_price_fallback"};const a=i/s;return a<ls||a>cs?{rate:1,realizedUnitRevenue:s,source:"menu_price_quality_fallback"}:{rate:ie(dt(a,0,1)),realizedUnitRevenue:U(i),source:"toast_net_sales"}},zt=({realizedUnitRevenue:e,unitCost:t,weeklyUnits:s})=>{const i=e-t,a=i*s;return{unitContribution:U(i),weeklyFoodCost:U(t*s),weeklyContribution:U(a),marginPct:e>0?ie(i/e):null}},us=({currentPrice:e,proposedPrice:t,realizedUnitRevenue:s=null,weeklyUnits:i=0,foodCost:a=null,volumeDropPct:n=0}={})=>{const o=Me(e),l=Me(t),u=Math.max(ct(i)||0,0),p=dt(ct(n)||0,0,100),x=u*(1-p/100);if(o==null||l==null||!(u>0))return{available:!1,contributionAvailable:!1,volumeDropPct:p,current:null,proposed:null,weeklyRevenueDelta:null,weeklyContributionDelta:null,breakevenUnits:null,maxVolumeDropPct:null};const d=ds({currentPrice:o,realizedUnitRevenue:s}),g=d.realizedUnitRevenue||o,z=g+(l-o)*d.rate,b=g*u,y=z*x,c=a?.trusted===!0&&a?.showNumeric===!0?Me(a?.cost):null,m={menuPrice:U(o),realizedUnitRevenue:U(g),weeklyUnits:ie(u),weeklyRevenue:U(b)},f={menuPrice:U(l),realizedUnitRevenue:U(z),weeklyUnits:ie(x),weeklyRevenue:U(y)};let h=null,P=null;return c!=null&&(Object.assign(m,zt({realizedUnitRevenue:g,unitCost:c,weeklyUnits:u})),Object.assign(f,zt({realizedUnitRevenue:z,unitCost:c,weeklyUnits:x})),f.unitContribution>0&&(h=Math.max(m.weeklyContribution/f.unitContribution,0),P=u>0?dt((1-h/u)*100,0,100):null)),{available:!0,contributionAvailable:c!=null,volumeDropPct:p,capture:d,current:m,proposed:f,weeklyRevenueDelta:U(f.weeklyRevenue-m.weeklyRevenue),weeklyContributionDelta:c==null?null:U(f.weeklyContribution-m.weeklyContribution),breakevenUnits:ie(h),maxVolumeDropPct:ie(P)}},rr=(e={})=>({deterministic:!0,demandPredicted:!1,scenarios:tr.map(t=>us({...e,volumeDropPct:t}))}),Ee=(e={},t=0)=>{const s=Number(t)||0;return(e?.scenarios||[]).find(i=>i.volumeDropPct===s)||null},sr=({impacts:e=[],volumeDropPct:t=0}={})=>{const s=(Array.isArray(e)?e:[]).map(n=>Ee(n,t)).filter(n=>n?.available===!0),i=s.filter(n=>n.contributionAvailable===!0),a=(n,o)=>U(n.reduce((l,u)=>l+(Number(u?.[o])||0),0));return{volumeDropPct:Number(t)||0,itemCount:s.length,trustedItemCount:i.length,trustedCoveragePct:s.length?ie(i.length/s.length):0,weeklyRevenueDelta:a(s,"weeklyRevenueDelta"),weeklyContributionDelta:i.length?a(i,"weeklyContributionDelta"):null,currentWeeklyContribution:i.length?U(i.reduce((n,o)=>n+(Number(o.current?.weeklyContribution)||0),0)):null,proposedWeeklyContribution:i.length?U(i.reduce((n,o)=>n+(Number(o.proposed?.weeklyContribution)||0),0)):null}},O=Object.freeze({PREMIUM:"tier1",CORE:"tier2",VALUE:"tier3"}),ir=Object.freeze([Object.freeze({id:O.PREMIUM,tier:"Tier 1",label:"Premium"}),Object.freeze({id:O.CORE,tier:"Tier 2",label:"Core"}),Object.freeze({id:O.VALUE,tier:"Tier 3",label:"Value"}
1)]),ms=Object.freeze({minSharedItems:3,minOverlapPct:.25,minIndexCoveragePct:.25,incomeWeight:.65,competitorWeight:.35,incomeSensitivity:.35,competitorSensitivity:.35,competitorPriceBenchmark:2,minCompetitorsForHighConfidence:5,minCompetitorPriceCoverage:.25,minMarketIndex:.8,maxMarketIndex:1.2,fallbackPremiumIndex:1.04,fallbackCoreIndex:1,fallbackValueIndex:.96}),oe=e=>String(e||"").trim().replace(/\s+/g," "),_e=e=>oe(e).toLowerCase(),fe=e=>{if(e==null||e===""||typeof e=="boolean")return null;const t=Number(e);return Number.isFinite(t)?t:null},$=e=>{const t=fe(e);return t!=null&&t>0?t:null},Q=e=>Number(Number(e||0).toFixed(6)),Ct=e=>Number(Number(e||0).toFixed(2)),Be=(e,t,s)=>Math.min(Math.max(e,t),s),ve=(e=[])=>{const t=e.map(fe).filter(i=>i!=null).sort((i,a)=>i-a);if(!t.length)return null;const s=Math.floor(t.length/2);return t.length%2?t[s]:(t[s-1]+t[s])/2},Pt=(e=[],t=.5)=>{const s=e.map(fe).filter(l=>l!=null).sort((l,u)=>l-u);if(!s.length)return null;if(s.length===1)return s[0];const i=Be(t,0,1)*(s.length-1),a=Math.floor(i),n=Math.ceil(i),o=i-a;return s[a]+(s[n]-s[a])*o},nr=(e={})=>({...ms,...e||{}}),ps=(e={})=>{const t=new Map,s=new Map;return(Array.isArray(e?.items)?e.items:[]).forEach(i=>{const a=_e(i?.itemKey||i?.itemName);a&&(s.set(a,oe(i?.itemName)||a),Object.entries(i?.byStore||{}).forEach(([n,o])=>{const l=oe(n),u=$(o?.avgPrice);if(!l||u==null)return;const p=t.get(l)||new Map;p.set(a,{price:u,qty:Math.max(fe(o?.qty)||0,0)}),t.set(l,p)}))}),{storeItems:t,itemNames:s}},xs=({stores:e,storeItems:t,config:s})=>{const i=[],a=new Map(e.map(n=>[n,new Set]));return e.forEach((n,o)=>{e.slice(o+1).forEach(l=>{const u=t.get(n)||new Map,p=t.get(l)||new Map,x=[...u.keys()].filter(b=>p.has(b)),d=Math.max(Math.min(u.size,p.size),1),g=x.length/d,z=x.length>=s.minSharedItems&&g>=s.minOverlapPct;z&&(a.get(n).add(l),a.get(l).add(n)),i.push({left:n,right:l,sharedItemCount:x.length,overlapPct:Q(g),comparable:z})})}),{pairs:i,adjacency:a}},gs=({stores:e,adjacency:t})=>{const s=new Set,i=[];return e.forEach(a=>{if(s.has(a))return;const n=[a],o=[];for(s.add(a);n.length;){const l=n.shift();o.push(l),[...t.get(l)||[]].sort().forEach(u=>{s.has(u)||(s.add(u),n.push(u))})}i.push(o.sort())}),i.sort((a,n)=>a[0].localeCompare(n[0])).map((a,n)=>({id:`cohort-${n+1}`,stores:a}))},bs=({store:e,cohortStores:t,storeItems:s,config:i})=>{const a=s.get(e)||new Map,n=[];a.forEach((u,p)=>{const x=t.map(g=>$(s.get(g)?.get(p)?.price)).filter(g=>g!=null),d=ve(x);x.length>=2&&d>0&&n.push(u.price/d)});const o=a.size>0?n.length/a.size:0,l=t.length>=2&&n.length>=i.minSharedItems&&o>=i.minIndexCoveragePct;return{store:e,priceIndex:Q(ve(n)||1),comparableItemCount:n.length,itemCount:a.size,coveragePct:Q(o),reliable:l,confidence:l?"high":n.length?"medium":"low"}},Te=(e,t,s)=>{const i=_e(e?.[t]);return i&&s.find(a=>_e(a)===i)||null},It=({candidates:e,target:t,excluded:s=new Set})=>e.filter(i=>!s.has(i.store)).sort((i,a)=>Math.abs(i.priceIndex-t)-Math.abs(a.priceIndex-t)||i.store.localeCompare(a.store))[0]||null,hs=({metrics:e,overrides:t,config:s})=>{const i=e.filter(v=>v.reliable),a=i.map(v=>v.priceIndex),n=new Map(e.map(v=>[v.store,v])),o=new Set,l=Te(t,O.PREMIUM,e.map(v=>v.store)),u=n.get(l)?.reliable?l:null,p=u?n.get(u):[...i].sort((v,j)=>j.priceIndex-v.priceIndex||v.store.localeCompare(j.store))[0]||null;p&&o.add(p.store);const x=Te(t,O.CORE,e.map(v=>v.store)),d=n.get(x)?.reliable?x:null,g=ve(a)||s.fallbackCoreIndex,z=d?n.get(d):It({candidates:i,target:g,excluded:o});z&&o.add(z.store);const b=Te(t,O.VALUE,e.map(v=>v.store)),y=n.get(b)?.reliable?b:null,c=Pt(a,.25)||s.fallbackValueIndex,m=y?n.get(y):It({candidates:i,target:c,excluded:o}),f=z?.priceIndex||g||s.fallbackCoreIndex,h=p?.priceIndex||Pt(a,.75)||s.fallbackPremiumIndex,P=m?.priceIndex||c||s.fallbackValueIndex,I={[O.PREMIUM]:Math.max(h,f),[O.CORE]:f,[O.VALUE]:Math.min(P,f)},M={[O.PREMIUM]:p,[O.CORE]:z,[O.VALUE]:m};return ir.map(v=>{const j=M[v.id],S=j?.reliable===!0&&Te(t,v.id,e.map(C=>C.store))===j?.store;return{...v,priceIndex:Q(I[v.id]),referenceStore:j?.store||null,referenceReliable:j?.reliable===!0,source:S?"corporate_override":j?"cohort_observed":"deterministic_fallback"}})},fs=e=>{const t=oe(e).match(/\${1,4}/gu)||[];return t.length?Math.max(...t.map(s=>s.length)):null},ar=(e={})=>{const t=e?.metrics||{},s=$(t.competitorCount??e?.source?.competitorCount)||0,i=$(t.avgPriceLevel)||fs(e?.priceTier),a=$(t.priceSampleC
1ount)||(i!=null?s:0),n=s>0?Be(fe(t.priceCoveragePct)??a/s,0,1):0;return{available:e?.status==="available"&&s>0,competitorCount:s,avgPriceLevel:i,priceSampleCount:a,priceCoveragePct:Q(n),avgRating:$(t.avgRating),highRatedCount:Math.max(fe(t.highRatedCount)||0,0)}},vs=({demographics:e={},competitorContext:t={},incomeBenchmark:s=null,competitorPriceBenchmark:i=null,config:a={}}={})=>{const n=nr(a),o=ar(t),l=$(e?.medianIncome),u=l!=null&&$(s)!=null?l/s:e?.available!==!1?$(e?.incomeIndex):null,p=o.available&&o.avgPriceLevel!=null?o.avgPriceLevel/($(i)||n.competitorPriceBenchmark):null,x=u!=null?Be(1+(u-1)*n.incomeSensitivity,n.minMarketIndex,n.maxMarketIndex):null,d=p!=null?Be(1+(p-1)*n.competitorSensitivity,n.minMarketIndex,n.maxMarketIndex):null,g=[x==null?null:{id:"census",value:x,weight:n.incomeWeight},d==null?null:{id:"competitor_price_posture",value:d,weight:n.competitorWeight}].filter(Boolean),z=g.reduce((m,f)=>m+f.weight,0),b=z>0?g.reduce((m,f)=>m+f.value*f.weight,0)/z:1,y=o.available&&o.competitorCount>=n.minCompetitorsForHighConfidence&&o.priceCoveragePct>=n.minCompetitorPriceCoverage,c=x!=null&&y?"high":g.length>0?"medium":"low";return{marketIndex:Q(b),confidence:c,fallback:g.length===0,signals:g.map(m=>({id:m.id,factor:Q(m.value),weight:Q(m.weight/z)})),census:{available:x!=null,medianIncome:l,benchmark:$(s),factor:x==null?null:Q(x)},competitor:{...o,factor:d==null?null:Q(d),affectsPriceThrough:d==null?null:"broad_price_posture",densityAndRatingsAffectPrice:!1}}},ys=(e,t)=>[...t].sort((s,i)=>Math.abs(s.priceIndex-e)-Math.abs(i.priceIndex-e)||(s.id===O.CORE?-1:i.id===O.CORE?1:0))[0]||null,Ns=({cohort:e,items:t,storeItems:s,guardrails:i})=>{const a={};return t.forEach(n=>{const o=_e(n?.itemKey||n?.itemName);if(!o)return;const l=ve(e.stores.map(d=>$(s.get(d)?.get(o)?.price)).filter(d=>d!=null));if(!(l>0))return;const u=e.tiers.map(d=>{const g=$(s.get(d.referenceStore)?.get(o)?.price);return{...d,price:X(g||l*d.priceIndex,i),itemPriceSource:g?"reference_store":"cohort_index"}}),p=u.find(d=>d.id===O.CORE)?.price||l,x=u.map(d=>({...d,price:Ct(d.id===O.PREMIUM?Math.max(d.price,p):d.id===O.VALUE?Math.min(d.price,p):d.price)}));a[o]={itemKey:o,itemName:oe(n?.itemName)||o,cohortMedianPrice:Ct(l),tiers:x}}),a},js=({baseline:e={},demographics:t={},competitorContextByStore:s={},referenceStoreOverrides:i={},config:a={},guardrails:n={}}={})=>{const o=nr(a),{storeItems:l,itemNames:u}=ps(e),p=[...l.keys()].sort(),{pairs:x,adjacency:d}=xs({stores:p,storeItems:l,config:o}),g=gs({stores:p,adjacency:d}).map(v=>{const j=v.stores.map(S=>bs({store:S,cohortStores:v.stores,storeItems:l,config:o}));return{...v,storeMetrics:j,tiers:hs({metrics:j,overrides:i,config:o})}}),z=[...g].sort((v,j)=>j.stores.length-v.stores.length||v.id.localeCompare(j.id))[0]||null,b=Object.values(t?.byStore||{}).map(v=>$(v?.medianIncome)).filter(v=>v!=null),y=$(a?.incomeBenchmark),c=$(t?.nationalMedianIncome),m=y||c||$(t?.chainMeanIncome)||ve(b),f=Object.values(s||{}).map(ar).filter(v=>v.available&&v.avgPriceLevel!=null).map(v=>v.avgPriceLevel),h=$(a?.competitorPriceBenchmark)||ve(f)||o.competitorPriceBenchmark,P=[...new Set([...p,...Object.keys(t?.byStore||{}).map(oe).filter(Boolean)])].sort(),I={};P.forEach(v=>{const j=g.find(k=>k.stores.includes(v))||z,S=j?.storeMetrics.find(k=>k.store===v)||null,C=vs({demographics:t?.byStore?.[v]||{},competitorContext:s?.[v]||{},incomeBenchmark:m,competitorPriceBenchmark:h,config:o}),R=ys(C.marketIndex,j?.tiers||[]),N=(j?.tiers||[]).every(k=>k.referenceReliable===!0);I[v]={store:v,cohortId:j?.id||null,comparisonStatus:S?.reliable?"comparable":S?"limited_overlap":"market_only",pricingIndex:S?.priceIndex||null,comparableItemCount:S?.comparableItemCount||0,comparisonCoveragePct:S?.coveragePct||0,tierReady:N,market:C,recommendedTierId:R?.id||O.CORE,recommendedTier:R||ir[1]}});const M={};return g.forEach(v=>{M[v.id]=Ns({cohort:v,items:Array.isArray(e?.items)?e.items:[],storeItems:l,guardrails:n})}),{version:1,deterministic:!0,legal:{nonBinding:!0,exactCompetitorMenuPricesUsed:!1,writesPrices:!1},config:{minSharedItems:o.minSharedItems,minOverlapPct:o.minOverlapPct,incomeWeight:o.incomeWeight,competitorWeight:o.competitorWeight},benchmarks:{income:m||null,incomeSource:y?"configured":c?"national":"cohort_fallback",competitorPriceLevel:h,competitorSource:$(a?.competitorPriceBenchmark)?"configured":"cohort_fallback"},pairs:x,cohorts:g,primaryCohortId:z?.id||null,byStore:I,itemTiersByCohort:M,itemNames:Object.fromEntries(u)}},Ss=({program:e={},store:t="",itemKey:s=""}={})=>{const i=e?.byStore?.[oe(t)],a=i?.cohortId?e?.itemTiersByCohort?.[i.cohortId]?.[_e(s)]:null;return{store:i||null,item:a||null,tiers:a?.tiers||[],recommendedTierId:i?.recommendedTierId||O.CORE}},E=(e,t=0)=>{const s=Number(e);return Number.isFinite(s)?s:t},Ye=Object.freeze({UNDER:"under",AT:"at",OVER:"over"}),Pe=Object.freeze({PREMIUM:O.PREMIUM,CORE:O.CORE,STANDARD:O.CORE,VALUE:O.VALUE}),wt=Object.freeze({quarter:.25,half:.5,whole:1,none:.01}),Ke=e=>Math.round(E(e)*100)/100,zs=(e={})=>wt[String(e?.rounding||"none").toLowerCase()]||wt.none,me=(e,t)=>
1{const s=X(e,t);return s>0?s:0},Cs=(e,t,s)=>e>=t?Math.max(Ke(t-s),s):e,Mt=(e,t,s)=>e<=t?Ke(t+s):e,Ps=({targetFoodCostPct:e=0,targetMarginPct:t=null,foodCostPct:s=0}={})=>{const i=E(e||s);if(i>0&&i<1)return i;const a=E(t);return a>0&&a<1?1-a:0},ge=({price:e=0,foodCost:t=null}={})=>{const s=E(e),i=E(t?.cost);if(!(s>0)||!(i>0)||t?.trusted!==!0)return{trusted:!1,grossProfit:null,marginPct:null,foodCostPct:null,helper:"estimate · pending real invoice data"};const a=s-i;return{trusted:!0,grossProfit:a,marginPct:a/s*100,foodCostPct:i/s*100,helper:"invoice-sourced · pack-normalized · no ingredient gaps"}},Is=({foodCost:e=null,currentPrice:t=0,targetFoodCostPct:s=0,targetMarginPct:i=null,guardrails:a={}}={})=>{const n=E(e?.cost),o=Ps({targetFoodCostPct:s,targetMarginPct:i});if(e?.trusted!==!0||!(n>0)||!(o>0))return{available:!1,suggestedPrice:null,targetFoodCostPct:o||null,targetMarginPct:o>0?1-o:null,current:ge({price:t,foodCost:e}),suggested:ge({price:null,foodCost:e})};const l=X(Ht(n,o),a);return{available:l>0,suggestedPrice:l>0?l:null,targetFoodCostPct:o,targetMarginPct:1-o,current:ge({price:t,foodCost:e}),suggested:ge({price:l,foodCost:e})}},ws=({suggestedPrice:e=0,currentPrice:t=0,guardrails:s={},foodCost:i=null,tierOptions:a=[],defaultTierId:n=Pe.CORE}={})=>{const o=me(e,s);if(!(o>0))return{available:!1,tiers:[],slider:null,preview:ge({price:t,foodCost:i})};const l=zs(s),u=Mt(me(o*1.04,s),o,l),p=Cs(me(o*.96,s),o,l),x=(Array.isArray(a)?a:[]).map(f=>({...f,price:me(f?.price,s)})).filter(f=>f.id&&f.price>0),d=x.length?x:[{id:Pe.PREMIUM,tier:"Tier 1",label:"Premium",price:u},{id:Pe.CORE,tier:"Tier 2",label:"Core",price:o},{id:Pe.VALUE,tier:"Tier 3",label:"Value",price:p}],g=d.some(f=>f.id===n)?n:Pe.CORE,z=d.map(f=>f.price),b=Math.min(...z,o,t>0?t:o)*.95,y=Math.max(...z,o,t>0?t:o)*1.05,c=Math.max(l,me(b,s)),m=Math.max(Mt(me(y,s),c,l),c+l);return{available:!0,anchoredTo:o,defaultTierId:g,tiers:d,slider:{min:Ke(c),max:Ke(m),step:l,defaultPrice:o},preview:ge({price:o,foodCost:i})}},kt=(e=null)=>Hr(e),Ms=(e,t,s=.03)=>{const i=E(e),a=E(t);if(!(a>0)||!(i>0))return{rating:null,ratio:null,gapPct:null};const n=i/a,o=(i-a)/a*100;let l;return n<1-s?l=Ye.UNDER:n>1+s?l=Ye.OVER:l=Ye.AT,{rating:l,ratio:n,gapPct:o}},ks=({chainBaseline:e,incomeIndex:t=1,currentPrice:s=0,mixWeight:i=0,guardrails:a={},atMarketPct:n=.03,cost:o=null,foodCostPct:l=0,foodCost:u=null,targetFoodCostPct:p=0,targetMarginPct:x=null,maxMovePct:d=null,tierSuggestedPrice:g=null}={})=>{const z=E(e),b=[];if(!(z>0))return{available:!1,suggestedPrice:null,rating:null,ratio:null,gapPct:null,opportunityRaw:0,flags:[{code:"no_market_baseline",message:"No market price for this item yet."}]};const y=E(t,1)>0?E(t,1):1,c=E(g),m=c>0?X(c,a):X(z*y,a);let f=m;c>0&&b.push({code:"franchise_tier_applied",message:"Built from comparable franchise prices and local market tier."});const h=Is({foodCost:u,currentPrice:s,targetFoodCostPct:p||l,targetMarginPct:x,guardrails:a});if(h.available&&h.suggestedPrice>0&&(h.suggestedPrice>f?(f=h.suggestedPrice,b.push({code:"margin_target_applied",message:"Raised to the trusted-cost margin target."})):b.push({code:"margin_target_met",message:"The market tier already meets the trusted-cost margin target."})),!h.available&&o!=null&&E(o)>0&&E(l)>0){const S=X(Ht(E(o),E(l)),a);S>f&&(f=S,b.push({code:"cost_floor_applied",message:"Raised to the cost-target floor."}))}const P=E(s);if(d!=null&&E(d)>0&&P>0){const S=P*(1+E(d)),C=P*(1-E(d));f>S?(f=X(S,a),b.push({code:"phase_in_capped",message:"Capped to the per-cycle move limit."})):f<C&&(f=X(C,a),b.push({code:"phase_in_capped",message:"Capped to the per-cycle move limit."}))}const{rating:I,ratio:M,gapPct:v}=Ms(s,f,n),j=(f>0?Math.abs(P-f)/f:0)*Math.max(E(i),0);return{available:!0,suggestedPrice:f,marketSuggestedPrice:m,marginAware:h,rating:I,ratio:M,gapPct:v,opportunityRaw:j,flags:b}},Rs=({baseline:e,demographics:t,guardrails:s={},atMarketPct:i=.03,costByItem:a={},foodCostPct:n=0,targetFoodCostPct:o=0,targetMarginPct:l=null,foodCostByRecipeId:u={},foodCostByItemKey:p={},competitorContextByStoreItem:x={},tierReferenceStores:d={},tierConfig:g={},disclaimer:z=""}={})=>{const b=e&&Array.isArray(e.items)?e.items:[],y=E(e&&e.totalChainQty),c=t&&t.byStore||{},m=[],f={};
1(e&&e.stores||[]).forEach(N=>{f[N]=kt(x[N]||null)});const h=js({baseline:e,demographics:t,competitorContextByStore:f,referenceStoreOverrides:d,config:g,guardrails:s});b.forEach(N=>{const k=E(N.chainAvgPrice);Object.entries(N.byStore||{}).forEach(([D,F])=>{const L=c[D]||{incomeIndex:1,available:!1},G=E(F.qty),ce=y>0?G/y:0,K=Ss({program:h,store:D,itemKey:N.itemKey}),Ne=K.tiers.find(He=>He.id===K.recommendedTierId)?.price,je=K.store?.tierReady===!0,de=os({recipeId:N.recipeId,itemKey:N.itemKey,itemName:N.itemName,foodCostByRecipeId:u,foodCostByItemKey:p}),H=ks({chainBaseline:k,incomeIndex:L.incomeIndex,currentPrice:F.avgPrice,mixWeight:ce,guardrails:s,atMarketPct:i,cost:a[N.itemKey]!=null?a[N.itemKey]:null,foodCostPct:n,foodCost:de,targetFoodCostPct:o,targetMarginPct:l,tierSuggestedPrice:je?Ne:null}),Se=[...H.flags];L.available===!1&&Se.push({code:"demographic_unavailable",message:"Demographic data unavailable for this city — using a neutral index."});const ze=Math.max(E(F.reportingWeeks,E(e&&e.windowDays,90)/7),1),Ae=ze>0?G/ze:0,ue=E(F.avgPrice),A=rr({currentPrice:ue,proposedPrice:H.suggestedPrice,realizedUnitRevenue:F.realizedUnitRevenue,weeklyUnits:Ae,foodCost:de}),We=Ee(A,0)?.weeklyRevenueDelta??null,qe=`${D}__${N.itemKey}`,Ge=ws({suggestedPrice:H.suggestedPrice,currentPrice:ue,guardrails:s,foodCost:de,tierOptions:je?K.tiers:[],defaultTierId:K.recommendedTierId});m.push({itemKey:N.itemKey,itemName:N.itemName,rawName:N.rawName,category:N.category||"",subcategory:N.subcategory||"",nameResolved:N.nameResolved!==!1,recipeId:N.recipeId||"",store:D,currentPrice:ue>0?ue:null,chainAvgPrice:k>0?k:null,suggestedPrice:H.suggestedPrice,marketSuggestedPrice:H.marketSuggestedPrice,marginAware:H.marginAware,foodCost:de,financialImpact:A,pricing:Ge,tierModel:{cohortId:K.store?.cohortId||null,comparisonStatus:K.store?.comparisonStatus||"market_only",tierReady:je,pricingIndex:K.store?.pricingIndex||null,market:K.store?.market||null,recommendedTierId:K.recommendedTierId,recommendedTier:K.store?.recommendedTier||null,item:K.item},competitorContext:kt(x[qe]||x[D]||x[N.itemKey]||x[N.itemName]||null),rating:H.rating,gapPct:H.gapPct,opportunityRaw:H.opportunityRaw,estWeeklyImpact:We,weeklyUnits:Ae,reportingWeeks:ze,reportingCoveragePct:E(F.reportingCoveragePct),realizedUnitRevenue:F.realizedUnitRevenue!=null?E(F.realizedUnitRevenue):null,mixWeight:ce,qty:G,flags:Se})})});const P=m.reduce((N,k)=>Math.max(N,k.opportunityRaw),0);m.forEach(N=>{N.opportunityScore=P>0?Math.round(N.opportunityRaw/P*100):0});const I={},M={};m.forEach(N=>{const k=I[N.store]||{store:N.store,totalOpportunity:0,count:0,under:0,at:0,over:0};k.totalOpportunity+=N.opportunityScore,k.count+=1,N.rating&&(k[N.rating]+=1),I[N.store]=k;const D=M[N.itemKey]||{itemKey:N.itemKey,itemName:N.itemName,totalOpportunity:0,count:0};D.totalOpportunity+=N.opportunityScore,D.count+=1,M[N.itemKey]=D});const v={};m.forEach(N=>{N.estWeeklyImpact>0&&(v[N.store]=(v[N.store]||0)+N.estWeeklyImpact)});const j=Object.entries(v).sort((N,k)=>k[1]-N[1])[0]?.[0]||null,S=m.filter(N=>N.rating==="under"&&N.estWeeklyImpact>0).reduce((N,k)=>N+k.estWeeklyImpact,0)*(52/12),C=Object.fromEntries((e&&e.stores||[]).map(N=>{const k=m.filter(D=>D.store===N).map(D=>D.financialImpact);return[N,{scenarios:tr.map(D=>sr({impacts:k,volumeDropPct:D}))}]})),R=Object.values(C).map(N=>N.scenarios.find(k=>k.volumeDropPct===0)).reduce((N,k)=>N+Math.max(Number(k?.weeklyContributionDelta)||0,0),0)*(52/12);return{rows:m,summary:{underCount:m.filter(N=>N.rating==="under").length,atCount:m.filter(N=>N.rating==="at").length,overCount:m.filter(N=>N.rating==="over").length,monthlyOpportunity:S,monthlyContributionOpportunity:R,topStore:j},rollups:{byStore:Object.values(I).sort((N,k)=>k.totalOpportunity-N.totalOpportunity),byItem:Object.values(M).sort((N,k)=>k.totalOpportunity-N.totalOpportunity),financialByStore:C},stores:e&&e.stores||[],storeCoverage:e&&e.storeCoverage||{},tierProgram:h,disclaimer:z}},_s=1440*60*1e3,Z=e=>String(e||"").trim().replace(/\s+/g," "),or=e=>Z(e).toLowerCase().replace(/[^a-z0-9]+/g," ").trim(),Y=e=>{if(e==null||e===""||typeof e=="boolean")return null;const t=Number(e);return Number.isFinite(t)?t:null},Xe=(e,t)=>t>0?e/t:0,Es=(e,t=0,s=1)=>Math.min(Math.max(e,t),s),Rt=(e,t)=>
1{const s=Date.parse(e),i=typeof t=="number"?t:Date.parse(t);return!Number.isFinite(s)||!Number.isFinite(i)?null:Math.max(Math.floor((i-s)/_s),0)},As=e=>e?.foodCost?.trusted===!0&&e?.foodCost?.showNumeric===!0,Ts=({rows:e=[],storeCoverage:t={},asOf:s=Date.now(),minHistoryDays:i=28,minObservedDays:a=14,minCoveragePct:n=.5,minItemCoveragePct:o=.8,competitorFreshDays:l=45}={})=>{const u=[...new Set([...Object.keys(t||{}),...(Array.isArray(e)?e:[]).map(x=>Z(x?.store)).filter(Boolean)])].sort(),p={};return u.forEach(x=>{const d=(Array.isArray(e)?e:[]).filter(k=>Z(k?.store)===x),g=d.length,z=t?.[x]||{},b=Xe(d.filter(k=>Y(k?.currentPrice)>0).length,g),y=Xe(d.filter(k=>Z(k?.recipeId)&&k?.nameResolved!==!1).length,g),c=Xe(d.filter(As).length,g),m=Math.max(Y(z?.calendarDays)||0,0),f=Math.max(Y(z?.observedBusinessDays)||0,0),h=Es(Y(z?.reportingCoveragePct)||0),P=Rt(z?.lastBusinessDate,s),I=d.some(k=>k?.tierModel?.market?.census?.available===!0),M=d.find(k=>k?.competitorContext?.status==="available")?.competitorContext||null,v=Rt(M?.source?.fetchedAt,s),j=M?.status==="available"&&v!=null&&v<=l,S=[{id:"toast_history",required:!0,ready:m>=i&&f>=a&&h>=n&&P!=null&&P<=7,value:f},{id:"menu_prices",required:!0,ready:g>0&&b>=.95,value:b},{id:"recipe_links",required:!0,ready:g>0&&y>=o,value:y},{id:"trusted_costs",required:!0,ready:g>0&&c>=o,value:c},{id:"census",required:!0,ready:I,value:I},{id:"competitors",required:!1,ready:j,value:v}],C=S.filter(k=>k.required),R=C.filter(k=>k.ready).length,N=Math.round((S[0].ready?20:0)+(S[1].ready?20:0)+(S[2].ready?15:0)+(S[3].ready?25:0)+(S[4].ready?10:0)+(S[5].ready?10:0));p[x]={store:x,status:R===C.length?j?"strong":"ready":S[0].ready&&S[1].ready?"limited":"building",score:N,checks:S,itemCount:g,priceCoveragePct:b,recipeCoveragePct:y,trustedCostCoveragePct:c,history:{calendarDays:m,observedBusinessDays:f,reportingCoveragePct:h,latestBusinessDate:z?.lastBusinessDate||null,latestSalesAgeDays:P},censusAvailable:I,competitorFresh:j,competitorAgeDays:v,readyForContribution:S[1].ready&&S[2].ready&&S[3].ready,readyForOutcomeTracking:S[0].ready&&S[1].ready}}),{deterministic:!0,byStore:p}},_t=/(\d{1,2}(?:\.\d+)?)\s*(?:"|\u2033|in\.?\b|inch(?:es)?\b)/i,Ds=e=>{const t=Z(e),s=t.match(_t);if(!s)return null;const i=Y(s[1]);if(!(i>0))return null;const a=or(t.replace(_t," ").replace(/\b(size|pizza|pie)\b/gi," "));return a.length<3?null:{size:i,family:a}},Et=({items:e,field:t,minGap:s})=>{const i=[];for(let a=1;a<e.length;a+=1){const n=e[a-1],o=e[a],l=Y(n?.[t]),u=Y(o?.[t]);!(l>0)||!(u>0)||u-l<s&&i.push({code:u<l?`${t}_inversion`:`${t}_compressed`,field:t,smaller:{itemKey:n.itemKey,itemName:n.itemName,size:n.size,price:l},larger:{itemKey:o.itemKey,itemName:o.itemName,size:o.size,price:u},requiredGap:s})}return i},Os=({rows:e=[],minGap:t=.25}={})=>{const s=new Map;
1(Array.isArray(e)?e:[]).forEach(n=>{const o=Ds(n?.itemName),l=Z(n?.store);if(!o||!l)return;const u=`${l}__${or(n?.category||n?.subcategory||"menu")}__${o.family}`,p=s.get(u)||{id:u,store:l,category:Z(n?.category||n?.subcategory||""),family:o.family,items:[]};p.items.push({itemKey:n?.itemKey,itemName:n?.itemName,size:o.size,currentPrice:Y(n?.currentPrice),suggestedPrice:Y(n?.suggestedPrice)}),s.set(u,p)});const i=[...s.values()].filter(n=>new Set(n.items.map(o=>o.size)).size>=2).map(n=>{const o=[...n.items].sort((u,p)=>u.size-p.size||Z(u.itemName).localeCompare(Z(p.itemName))),l=[...Et({items:o,field:"currentPrice",minGap:t}),...Et({items:o,field:"suggestedPrice",minGap:t})];return{...n,items:o,issues:l,status:l.length?"review":"balanced"}}).sort((n,o)=>n.store.localeCompare(o.store)||n.family.localeCompare(o.family)),a={};return i.forEach(n=>{const o=a[n.store]||{store:n.store,groupCount:0,issueCount:0,groups:[]};o.groupCount+=1,o.issueCount+=n.issues.length,o.groups.push(n),a[n.store]=o}),Object.values(a).forEach(n=>{n.status=n.issueCount?"review":"balanced"}),{deterministic:!0,changesPrices:!1,groups:i,byStore:a}},$s=({rows:e=[],storeCoverage:t={},asOf:s=Date.now()}={})=>({readiness:Ts({rows:e,storeCoverage:t,asOf:s}),menuBalance:Os({rows:e})}),se=e=>String(e||"").trim().replace(/\s+/g," "),Ls=e=>se(e).toLowerCase().replace(/\s+/g," "),De=e=>{if(e==null||e===""||typeof e=="boolean")return null;const t=Number(e);return Number.isFinite(t)?t:null},q=(e,t=2)=>Number(Number(e||0).toFixed(t)),At=(e,t)=>e>0?q((t-e)/e*100,1):null,Tt=(e,t=null)=>{const s=e.length,i=e.reduce((x,d)=>x+d.units,0),a=e.reduce((x,d)=>x+d.netSales,0),n=s>0?e.reduce((x,d)=>x+(d.storeUnits>0?d.units/d.storeUnits:0),0)/s:0,o=s>0?i/s:0,l=s>0?a/s:0,u=t!=null&&t>0,p=u?l-o*t:null;return{dayCount:s,startDate:e[0]?.date||null,endDate:e[e.length-1]?.date||null,menuPrice:q(e.reduce((x,d)=>x+d.menuPrice,0)/Math.max(s,1)),unitsPerDay:q(o,1),netRevenuePerDay:q(l),realizedUnitRevenue:i>0?q(a/i):null,mixPct:q(n*100,1),contributionAvailable:u,estimatedContributionPerDay:u?q(p):null}},Fs=e=>e.reduce((t,s)=>{const i=t[t.length-1];return i&&Math.abs(i.menuPrice-s.menuPrice)<.001?(i.days.push(s),t):(t.push({menuPrice:s.menuPrice,days:[s]}),t)},[]),Us=({productMixDocs:e=[],reportRows:t=[],resolveName:s=null,isExcluded:i=null,minObservedDays:a=7,maxComparisonDays:n=28,minPriceChange:o=.25}={})=>{const l=Wt(Array.isArray(e)?e:[]),u=new Map,p=new Map;l.forEach(b=>{if(i&&i(b))return;const y=se((s?s(b):{name:b.itemName,resolved:!0})?.name||b.itemName),c=se(b.posItemId||b.sku).toLowerCase()||Ls(y||b.itemName),m=se(b.store),f=se(b.businessDate).slice(0,10),h=De(b.unitPrice??b.menuPrice??b.avgPrice),P=Math.max(De(b.quantitySold)||0,0),I=Math.max(De(b.netSales)||0,0);if(!m||!f||!c)return;const M=`${m}__${f}`;if(u.set(M,(u.get(M)||0)+P),!(h>0))return;const v=`${m}__${c}__${f}`,j=p.get(v)||{store:m,itemKey:c,itemName:y,date:f,units:0,netSales:0,menuPriceTotal:0,menuPriceWeight:0},S=P>0?P:1;j.units+=P,j.netSales+=I,j.menuPriceTotal+=h*S,j.menuPriceWeight+=S,p.set(v,j)});const x=new Map((Array.isArray(t)?t:[]).map(b=>{const y=b?.foodCost?.trusted===!0&&b?.foodCost?.showNumeric===!0?De(b?.foodCost?.cost):null;return[`${se(b?.store)}__${se(b?.itemKey).toLowerCase()}`,y]})),d=new Map;p.forEach(b=>{const y=`${b.store}__${b.itemKey}`,c=d.get(y)||[];c.push({...b,menuPrice:b.menuPriceWeight>0?q(b.menuPriceTotal/b.menuPriceWeight):null,storeUnits:u.get(`${b.store}__${b.date}`)||0}),d.set(y,c)});const g=[];d.forEach((b,y)=>{const c=Fs(b.sort((S,C)=>S.date.localeCompare(C.date)));let m=null;for(let S=c.length-1;S>0;S-=1){const C=c[S-1],R=c[S];if(!(C.days.length<a||R.days.length<a)&&!(Math.abs(R.menuPrice-C.menuPrice)<o)){m={beforeEpisode:C,afterEpisode:R};break}}if(!m)return;const f=Math.min(m.beforeEpisode.days.length,m.afterEpisode.days.length,n),h=m.beforeEpisode.days.slice(-f),P=m.afterEpisode.days.slice(-f),I=x.get(y),M=Tt(h,I),v=Tt(P,I),j=M.contributionAvailable&&v.contributionAvailable;g.push({id:y,store:P[0].store,itemKey:P[0].itemKey,itemName:P[0].itemName,changeDate:m.afterEpisode.days[0]?.date||null,direction:v.menuPrice>M.menuPrice?"increase":"decrease",comparisonDays:f,before:M,after:v,changes:{menuPrice:q(v.menuPrice-M.menuPrice),unitsPct:At(M.unitsPerDay,v.unitsPerDay),netRevenuePct:At(M.netRevenuePerDay,v.netRevenuePerDay),mixPoints:q(v.mixPct-M.mixPct,1),netRevenuePerWeek:q((v.netRevenuePerDay-M.netRevenuePerDay)*7),estimatedContributionPerWeek:j?q((v.estimatedContributionPerDay-M.estimatedContributionPerDay)*7):null},contributionAvailable:j,contributionBasis:j?"current_trusted_food_cost":"unavailable",observational:!0,causalClaim:!1,demandForecast:!1})}),g.sort((b,y)=>y.changeDate.localeCompare(b.changeDate)||b.itemName.localeCompare(y.itemName));const z={};return g.forEach(b=>{const y=z[b.store]||[];y.push(b),z[b.store]=y}),{deterministic:!0,observational:!0,outcomes:g,byStore:z}},Bs=["modifier","add-on","add on","addon","no ","sub ","extra ","side of","fee","service charge","gratuity","tip","tax","void","refund","discount","comp","open item","open food","misc","test item","gift card"],V=e=>String(e||"").replace(/\s+/g," ").trim(),lr=e=>V(e).toLowerCase().replace(/["']/g,"").replace(/[^a-z0-9]+/g," ").trim(),Ve=e=>
1lr(e).split(/\s+/).filter(Boolean),Ks=new Set(["test","sample","default","item"]),xe=e=>{const t=V(e);return!!(!t||/^[#0-9][0-9\-_.]*$/.test(t)||/^[A-Z0-9][A-Z0-9_\-]{2,}$/.test(t)&&!/\s/.test(t)&&/[0-9]/.test(t)||/^num[-_\s]*slices?\s*\|?\s*\d+$/i.test(t)||Ks.has(lr(t)))},ut=e=>{let t=V(e);return t?(t=t.replace(/^[#]?[0-9][0-9\-_.]*\s*[-:|]\s*/,""),t=t.replace(/^[A-Z0-9]{2,}[_\-]\s*/,""),t||(t=V(e)),t.replace(/\b[A-Z][A-Z0-9'&]+\b/g,s=>s.length<=2?s:s.charAt(0)+s.slice(1).toLowerCase())):""},Dt=(e={})=>{const t=V(e?.itemName||e?.name).toLowerCase();return t?Bs.some(s=>t.includes(s)):!0},Vs=e=>{const t=V(e).split(/\s*,{2,}\s*/).map(s=>ut(s)).filter(Boolean).filter(s=>!/^(uncategorized|food|menu|item|items)$/i.test(s));return t[t.length-1]||""},cr=e=>Ve(e).filter(t=>/^\d+(?:\.\d+)?$/.test(t)),Ws=e=>Ve(e).filter(t=>t.length>=3&&!/^\d/.test(t)),qs=(e={})=>[e?.itemName||e?.name,e?.menuName,e?.menu,e?.category,e?.subcategory].map(V).filter(Boolean).join(" "),Gs=(e,t={})=>{const s=cr(e);if(!s.length)return!0;const i=V(t?.itemName||t?.name);if(!i||xe(i))return!0;const a=new Set(Ve(qs(t)));return s.every(n=>a.has(n))},Hs=(e=[])=>{const t=(Array.isArray(e)?e:[]).map(s=>{const i=V(s?.name||s?.recipeName||s?.title),a=cr(i),n=Ws(i);return!i||!a.length||!n.length?null:{recipe:s,recipeId:V(s?.id||s?.recipeId||s?.name),name:i,numbers:a,words:n}}).filter(Boolean);return s=>{const i=new Set(Ve(s)),a=t.filter(o=>o.numbers.every(l=>i.has(l))&&o.words.some(l=>i.has(l)));if(a.length!==1)return null;const n=a[0];return{name:n.name,source:"categoryRecipeMatch",resolved:!0,recipeId:n.recipeId}}},Qs=(e=[])=>{const t=Array.isArray(e)?e:[],s=Nr(t),i=Hs(t);return(a={})=>{const n=jr(a,s),o=V(n?.recipe?.name),l=V(n?.binding?.recipeId||n?.recipe?.id||n?.recipe?.recipeId);if(o&&Gs(o,a))return{name:o,source:"recipe",resolved:!0,recipeId:l};const u=V(a?.itemName||a?.name),p=Vs(a?.category);if(p&&(!u||xe(u))){const g=i(p);return g||{name:p,source:"category",resolved:!0,recipeId:""}}const x=ut(u);if(x&&!xe(u))return{name:x,source:"raw",resolved:!xe(x),recipeId:""};const d=V(a?.menuName);return d&&!xe(d)?{name:ut(d),source:"menuName",resolved:!0,recipeId:""}:{name:x||u,source:"raw",resolved:!!x&&!xe(x),recipeId:""}}},Zs=["This SRP guidance is for informational purposes only. All Slice House franchisees are independently owned and operated, and each franchisee is solely responsible for setting its own prices. Nothing in this document should be interpreted as required pricing, mandated pricing, or an attempt to control a franchisee’s retail prices.","Any ranges or examples provided are non-binding recommendations meant to support franchisees in making their own independent pricing decisions based on local costs, competition, and market conditions."].join(" "),Ys=Object.freeze({CA:4,WA:4,NY:4,MA:4,CT:4,NJ:4,DC:4,HI:4,CO:3,AZ:3,IL:3,MD:3,OR:3,RI:3,VT:3,ME:3,MN:3,NV:3,FL:3,MI:3,VA:3,DE:3,NM:3,TX:2,GA:2,TN:2,NC:2,SC:2,AL:2,MS:2,LA:2,KY:2,IN:2,OH:2,OK:2,KS:2,WI:2,IA:2,ID:2,WY:2,ND:2,SD:2,PA:2,WV:2,MT:2,AR:2,NE:2,UT:2,MO:2,NH:2}),Xs=Object.freeze([Object.freeze({key:"cheese-slice",match:["cheese slice","cheese by the slice"],ranges:Object.freeze({2:{low:6,high:6.5},3:{low:6,high:6.5},4:{low:6.25,high:6.75}})}),Object.freeze({key:"specialty-slice",match:["specialty slice","specialty by the slice"],ranges:Object.freeze({2:{low:7,high:7.5},3:{low:7.25,high:7.75},4:{low:7.5,high:8}})}),Object.freeze({key:"xl-cheese-pie",match:["xl cheese","cheese pie","ny cheese"],ranges:Object.freeze({2:{low:34,high:36},3:{low:35,high:37},4:{low:36,high:38}})}),Object.freeze({key:"xl-specialty-pie",match:["xl specialty","specialty pie"],ranges:Object.freeze({2:{low:40,high:44},3:{low:42,high:45},4:{low:44,high:47}})}),Object.freeze({key:"sicilian-detroit",match:["sicilian","detroit"],ranges:Object.freeze({2:{low:35,high:38},3:{low:36,high:39},4:{low:37,high:40}})}),Object.freeze({key:"wings",match:["wings"],ranges:Object.freeze({2:{low:14,high:14.5},3:{low:14.5,high:15},4:{low:15,high:15.5}})}),Object.freeze({key:"meatballs",match:["meatball"],ranges:Object.freeze({2:{low:7,high:11},3:{low:7.25,high:11.25},4:{low:7.5,high:11.5}})}),Object.freeze({key:"salads",match:["salad"],ranges:Object.freeze({2:{low:9,high:12},3:{low:10,high:12.5},4:{low:10.5,high:13}})}),Object.freeze({key:"pasta",match:["pasta"],ranges:Object.freeze({2:{low:14,high:16},3:{low:14.5,high:16.5},4:{low:15,high:17}})})]),Js=Object.freeze({foodCostPct:.24,laborPct:.24,occupancyPct:.1}),ei=Object.freeze({rounding:"quarter",forbidNineEndings:!0,evenDollarThresholds:Object.freeze([3,5,6,10,20,30]),maxMovePct:.05,minDaysBetweenChanges:90,movesPerYear:2}),Je=Object.freeze({brandId:"slice-house",zoneTable:Ys,seedZone:3,baselineRanges:Xs,costTargets:J
1s,guardrails:ei,disclaimer:Zs}),ti=12,ri=(e=[])=>[...new Set((Array.isArray(e)?e:[]).map(t=>String(t||"").trim()).filter(Boolean))],si=({tenantId:e="",stores:t=[]}={})=>{const s=String(e||"").trim(),i=(0,w.useMemo)(()=>ri(t),[t]),a=i.join("|"),[n,o]=(0,w.useState)({}),[l,u]=(0,w.useState)({});(0,w.useEffect)(()=>{if(!s||!i.length){o({}),u({});return}u({});const g=i.map(z=>Ue(st(nt(Fe,Le.srpCompetitorSnapshots),we("tenantId","==",s),we("store","==",z),it(ti)),b=>{o(y=>({...y,[z]:b.docs.map(c=>({id:c.id,...c.data()}))})),u(y=>({...y,[z]:!0}))},()=>{o(b=>({...b,[z]:[]})),u(b=>({...b,[z]:!0}))}));return()=>g.forEach(z=>z())},[s,a]);const p=(0,w.useMemo)(()=>Object.values(n).flat(),[n]),x=(0,w.useMemo)(()=>Qr({snapshots:p}),[p]),d=!!s&&i.length>0&&i.some(g=>l[g]!==!0);return{competitorContextByStoreItem:x.byLookup,snapshots:p,loading:d}},ii=120,ni=500,ai=12e3,oi="Sales data is taking longer than expected for some stores. Showing what loaded; refresh to try again.",li=({tenantId:e="",tenant:t=null}={})=>{const s=String(e||"").trim(),[i,a]=(0,w.useState)([]),[n,o]=(0,w.useState)({}),[l,u]=(0,w.useState)({}),[p,x]=(0,w.useState)(""),d=(0,w.useMemo)(()=>{if(!t)return[];const b=ft(t)||[],y=new Set;return b.forEach(c=>{const m=typeof c=="string"?c:c?.name;if(!m)return;const f=vt({tenant:t,storeOptions:b,selectedStore:m})||m,h=String(f||"").trim();h&&y.add(h)}),[...y]},[t]),g=(0,w.useMemo)(()=>{if(!t)return{};const b=ft(t)||[],y={};return b.forEach(c=>{if(typeof c=="string")return;const m=c?.name,f=String(c?.zip||c?.zipCode||c?.postalCode||"").replace(/[^0-9]/g,"").slice(0,5);if(!m||f.length!==5)return;const h=String(vt({tenant:t,storeOptions:b,selectedStore:m})||m).trim();h&&(y[h]=f)}),y},[t]),z=d.join("|");return(0,w.useEffect)(()=>{if(!s){a([]);return}const b=Ue(st(nt(Fe,Le.recipes),we("tenantId","==",s),it(ni)),y=>a(y.docs.map(c=>({id:c.id,...c.data()})).filter(c=>c.isDeleted!==!0)),y=>{Gt(y,{module:"useSrpMarketData",action:"srp_recipes_query_failed"}),a([])});return()=>b()},[s]),(0,w.useEffect)(()=>{if(!s||!d.length){o({}),u({});return}u({}),x("");const b=[],y=d.map(c=>{const m=st(nt(Fe,Le.toastProductMix),we("tenantId","==",s),we("store","==",c),hr("businessDate","desc"),it(ii)),f=setTimeout(()=>{o(h=>Object.prototype.hasOwnProperty.call(h,c)?h:{...h,[c]:[]}),u(h=>({...h,[c]:!0})),x(oi)},ai);return b.push(f),Ue(m,h=>{clearTimeout(f),o(P=>({...P,[c]:h.docs.map(I=>({id:I.id,...I.data()}))})),u(P=>({...P,[c]:!0}))},()=>{clearTimeout(f),o(h=>({...h,[c]:[]})),u(h=>({...h,[c]:!0})),x("Could not load some stores' sales right now.")})});return()=>{b.forEach(c=>clearTimeout(c)),y.forEach(c=>c())}},[s,z]),{productMixDocs:(0,w.useMemo)(()=>Object.values(n).flat(),[n]),recipes:i,stores:d,storeZip:g,loading:!!s&&d.length>0&&d.some(b=>l[b]!==!0),error:p}},ci=e=>String(e||"").replace(/[^0-9]/g,"").slice(0,5),di=({enabled:e=!1,zips:t=[]}={})=>{const[s,i]=(0,w.useState)({}),a=(0,w.useRef)(new Set),n=(0,w.useMemo)(()=>[...new Set((Array.isArray(t)?t:[]).map(ci).filter(o=>o.length===5))],[t]);return(0,w.useEffect)(()=>{if(!e||!n.length){i({});return}let o=null;try{o=Kt(Bt,"resolveStoreDemographics")}catch{o=null}const l=n.map(u=>Ue(fr(Fe,Le.marketDemographics,u),p=>{if(p.exists()){const x=p.data()||{};x.available===!0&&Number(x.medianIncome)>0&&i(d=>({...d,[u]:{medianIncome:Number(x.medianIncome),population:Number(x.population)||null}}))}else o&&!a.current.has(u)&&(a.current.add(u),o({zip:u}).catch(()=>{}))},p=>{Gt(p,{module:"useCensusDemographics",action:"census_demographics_query_failed"})}));return()=>l.forEach(u=>u())},[e,n.join("|")]),{zipTable:s}},r=xr(),dr=52/12,W=e=>e==null||!Number.isFinite(Number(e))?null:`$${Number(e).toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`,mt=e=>e==null||!Number.isFinite(Number(e))?null:`$${Math.round(Number(e)).toLocaleString("en-US")}`,te=e=>{const t=Number(e);if(!Number.isFinite(t))return null;let s="";return t>0&&(s="+"),t<0&&(s="-"),`${s}${mt(Math.abs(t))}`},ne=e=>e==null||!Number.isFinite(Number(e))?null:`${Number(e).toFixed(1)}%`,pt=e=>
1e==null||!Number.isFinite(Number(e))?"0":Number(e).toLocaleString("en-US",{maximumFractionDigits:1}),ui=e=>{const t=Number(e);return Number.isFinite(t)?`${t>0?"+":""}${t.toFixed(1)}%`:null},mi=(e,t="en")=>{const s=Date.parse(`${String(e||"").slice(0,10)}T12:00:00Z`);return Number.isFinite(s)?new Intl.DateTimeFormat(t==="es"?"es-US":"en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(new Date(s)):String(e||"")},ye=e=>`${e.store}__${e.itemKey}`,pi=e=>e.foodCost?.trusted===!0&&e.foodCost?.showNumeric===!0,Ot=e=>Math.max(Number(Ee(e.financialImpact,0)?.weeklyContributionDelta)||Number(e.estWeeklyImpact)||0,0),ur=(e={},t=s=>s)=>t(`srpStudio.${e.id}`),bt=(e,t)=>rr({currentPrice:e.currentPrice,proposedPrice:t,realizedUnitRevenue:e.realizedUnitRevenue,weeklyUnits:e.weeklyUnits,foodCost:e.foodCost}),xi=(e,t,s)=>Ee(bt(e,t),s),et=({label:e,value:t,helper:s="",testId:i=""})=>(0,r.jsxs)("div",{className:"min-h-[92px] rounded-lg border border-zinc-200 bg-white px-4 py-3",children:[(0,r.jsx)("p",{className:"text-xs font-semibold text-zinc-600",children:e}),(0,r.jsx)("p",{"data-testid":i||void 0,className:"mt-1 text-xl font-semibold text-zinc-950",children:t}),s?(0,r.jsx)("p",{className:"mt-1 text-sm leading-5 text-zinc-600",children:s}):null]}),gi=({row:e,t})=>{const s=pi(e);return(0,r.jsxs)("div",{"data-testid":`srp-food-cost-${ye(e)}`,className:"mt-2",children:[(0,r.jsx)("p",{className:"text-xs font-medium text-zinc-600",children:t("srpStudio.foodCost")}),(0,r.jsx)("p",{className:`mt-0.5 text-sm font-semibold ${s?"text-emerald-700":"text-zinc-600"}`,children:s?e.foodCost.displayValue:t("srpStudio.pending")}),(0,r.jsx)("p",{className:"mt-0.5 text-xs leading-5 text-zinc-600",children:t(s?"srpStudio.verifiedFoodCost":"srpStudio.pendingFoodCost")})]})},bi=({value:e,onChange:t,t:s})=>(0,r.jsxs)("fieldset",{children:[(0,r.jsx)("legend",{className:"text-sm font-semibold text-zinc-950",children:s("srpStudio.scenarioLegend")}),(0,r.jsx)("div",{className:"mt-2 grid grid-cols-3 gap-2","data-testid":"srp-volume-scenarios",children:[{value:0,label:s("srpStudio.sameSales")},{value:5,label:s("srpStudio.fiveFewer")},{value:10,label:s("srpStudio.tenFewer")}].map(i=>(0,r.jsx)("button",{type:"button","aria-pressed":e===i.value,onClick:()=>t(i.value),className:`min-h-11 rounded-lg border px-3 py-2 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-brand-500/20 ${e===i.value?"border-brand-600 bg-brand-50 text-brand-900":"border-zinc-200 bg-white text-zinc-700 hover:bg-zinc-50"}`,children:i.label},i.value))}),(0,r.jsx)("p",{className:"mt-2 text-sm leading-5 text-zinc-600",children:s("srpStudio.scenarioCaveat")})]}),hi=({row:e,t})=>{const s=ye(e),i=e.competitorContext||{},a=i.status!=="available",n=i.source||{};return(0,r.jsxs)("section",{"data-testid":`srp-competitor-${s}`,className:"border-t border-zinc-200 py-5",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h2",{className:"text-base font-semibold text-zinc-950",children:t("srpStudio.nearbyMarket")}),(0,r.jsx)("p",{"data-testid":`srp-competitor-source-${s}`,className:"mt-1 text-sm leading-6 text-zinc-600",children:a?t("srpStudio.nearbyUpdating"):t("srpStudio.broadContext",{source:i.label})})]}),a?null:(0,r.jsx)("span",{translate:"no",className:"text-xs font-normal tracking-normal text-zinc-600",children:t("srpStudio.googleMaps")})]}),a?(0,r.jsx)("p",{"data-testid":`srp-competitor-helper-${s}`,className:"mt-3 text-sm leading-6 text-zinc-600",children:t("srpStudio.stillUseful")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("dl",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[[t("srpStudio.nearbyCompetitors"),i.density||t("srpStudio.notAvailable")],[t("srpStudio.highRatedPeers"),i.rating||t("srpStudio.notAvailable")],[t("srpStudio.typicalPrice"),i.priceTier||t("srpStudio.notAvailable")]].map(([o,l])=>(0,r.jsxs)("div",{className:"rounded-lg border border-zinc-200 bg-zinc-50 px-4 py-3",children:[(0,r.jsx)("dt",{className:"text-xs font-medium text-zinc-600",children:o}),(0,r.jsx)("dd",{className:"mt-1 text-sm font-semibold text-zinc-950",children:l})]},o))}),(0,r.jsx)("p",{"data-testid":`srp-competitor-helper-${s}`,className:"mt-3 text-sm leading-6 text-zinc-600",children:t("srpStudio.marketLegal",{radius:n.radiusLabel?`${n.radiusLabel}. `:""})})]})]})},fi=({readiness:e,t})=>
1{if(!e)return null;const s=Array.isArray(e.checks)?e.checks:[],i=s.filter(n=>n.ready).length,a=t(`srpStudio.readiness.${e.status}`);return(0,r.jsxs)("section",{"data-testid":"srp-readiness",className:"border-b border-zinc-200 py-5",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-xs font-semibold text-zinc-600",children:t("srpStudio.dataConfidence")}),(0,r.jsx)("h2",{className:"mt-1 text-lg font-semibold text-zinc-950",children:a}),(0,r.jsx)("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-zinc-600",children:t(`srpStudio.readinessHelper.${e.status}`)})]}),(0,r.jsx)("span",{className:"text-sm font-semibold text-zinc-700",children:t("srpStudio.checksReady",{ready:i,total:s.length})})]}),(0,r.jsxs)("details",{className:"mt-3",children:[(0,r.jsx)("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-semibold text-brand-700 focus:outline-none focus:ring-4 focus:ring-brand-500/20",children:t("srpStudio.seeDataChecks")}),(0,r.jsx)("ul",{className:"grid gap-2 pb-1 sm:grid-cols-2 lg:grid-cols-3",children:s.map(n=>(0,r.jsxs)("li",{className:"flex items-center justify-between gap-3 rounded-lg border border-zinc-200 bg-white px-3 py-3 text-sm",children:[(0,r.jsx)("span",{className:"font-medium text-zinc-800",children:t(`srpStudio.check.${n.id}`)}),(0,r.jsx)("span",{className:`font-semibold ${n.ready?"text-emerald-700":"text-amber-700"}`,children:n.ready?t("srpStudio.ready"):t("srpStudio.needsAttention")})]},n.id))})]})]})},vi=({outcomes:e,t,lang:s})=>{const i=Array.isArray(e)?e.slice(0,3):[];return i.length?(0,r.jsxs)("section",{"data-testid":"srp-observed-outcomes",className:"border-b border-zinc-200 py-5",children:[(0,r.jsx)("h2",{className:"text-lg font-semibold text-zinc-950",children:t("srpStudio.observedTitle")}),(0,r.jsx)("p",{className:"mt-1 text-sm leading-6 text-zinc-600",children:t("srpStudio.observedHelper")}),(0,r.jsx)("div",{className:"mt-4 grid gap-3 lg:grid-cols-3",children:i.map(a=>(0,r.jsxs)("article",{"data-testid":`srp-outcome-${a.store}__${a.itemKey}`,className:"rounded-lg border border-zinc-200 bg-white px-4 py-4",children:[(0,r.jsx)("p",{className:"text-xs font-semibold text-brand-700",children:mi(a.changeDate,s)}),(0,r.jsx)("h3",{className:"mt-1 text-base font-semibold text-zinc-950",children:a.itemName}),(0,r.jsx)("p",{className:"mt-2 text-sm leading-6 text-zinc-700",children:t("srpStudio.observedPrice",{before:W(a.before?.menuPrice),after:W(a.after?.menuPrice)})}),(0,r.jsxs)("dl",{className:"mt-3 grid grid-cols-2 gap-2",children:[(0,r.jsxs)("div",{className:"rounded-lg bg-zinc-50 px-3 py-2",children:[(0,r.jsx)("dt",{className:"text-xs text-zinc-600",children:t("srpStudio.unitsChange")}),(0,r.jsx)("dd",{className:"mt-1 text-sm font-semibold text-zinc-950",children:ui(a.changes?.unitsPct)||t("srpStudio.notAvailable")})]}),(0,r.jsxs)("div",{className:"rounded-lg bg-zinc-50 px-3 py-2",children:[(0,r.jsx)("dt",{className:"text-xs text-zinc-600",children:t("srpStudio.revenueChange")}),(0,r.jsxs)("dd",{className:"mt-1 text-sm font-semibold text-zinc-950",children:[te(a.changes?.netRevenuePerWeek)||t("srpStudio.notAvailable"),t("srpStudio.perWeekSuffix")]})]})]}),a.contributionAvailable?(0,r.jsx)("p",{className:"mt-3 text-sm leading-6 text-emerald-800",children:t("srpStudio.currentCostOutcome",{value:te(a.changes?.estimatedContributionPerWeek)})}):null,(0,r.jsx)("p",{className:"mt-2 text-xs leading-5 text-zinc-600",children:t("srpStudio.observedCaveat",{days:a.comparisonDays})})]},a.id))})]}):null},yi=({balance:e,t})=>{if(!e||!e.groupCount)return null;const s=e.groups.flatMap(i=>i.issues||[]).slice(0,3);return(0,r.jsxs)("section",{"data-testid":"srp-menu-balance",className:`border-b py-5 ${s.length?"border-amber-200":"border-zinc-200"}`,children:[(0,r.jsx)("h2",{className:"text-lg font-semibold text-zinc-950",children:t("srpStudio.menuBalanceTitle")}),(0,r.jsx)("p",{className:"mt-1 text-sm leading-6 text-zinc-600",children:s.length?t("srpStudio.menuBalanceReview",{count:e.issueCount}):t("srpStudio.menuBalanceGood",{count:e.groupCount})}),s.length?(0,r.jsx)("ul",{className:"mt-3 grid gap-2",children:s.map(i=>(0,r.jsx)("li",{className:"rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm leading-6 text-amber-950",children:t("srpStudio.menuBalanceIssue",{larger:i.larger.itemName,largerPrice:W(i.larger.price),smaller:i.smaller.itemName,smallerPrice:W(i.smaller.price)})},`${i.code}-${i.smaller.itemKey}-${i.larger.itemKey}`))}):null,(0,r.jsx)("p",{className:"mt-2 text-xs leading-5 text-zinc-600",children:t("srpStudio.menuBalanceCaveat")})]})},tt=({label:e,value:t,helper:s="",testId:i=""})=>(0,r.jsxs)("div",{className:"rounded-lg border border-zinc-200 bg-zinc-50 px-3 py-3",children:[(0,r.jsx)("p",{className:"text-xs font-medium text-zinc-600",children:e}),(0,r.jsx)("output",{"data-testid":i||void 0,className:"mt-1 block text-base font-semibold text-zinc-950","aria-live":"polite",children:t}),s?(0,r.jsx)("p",{className:"mt-1 text-xs leading-5 text-zinc-600",children:s}):null]}),Ni=({row:e,selectedPrice:t,onPriceChange:s,volumeDropPct:i,t:a})=>{const n=ye(e),o=e.pricing||{},l=Array.isArray(o.tiers)?o.tiers:[],u=o.slider||{},p=Number(u.step||.25),x=l.map(h=>Number(h.price)).filter(Number.isFinite),d=Number(u.min||Math.max(Number(e.currentPrice||t)-1,p)),g=Number(u.max||Number(e.suggestedPrice||t)+1),z=Math.min(d,...x),b=Math.max(g,...x),y=h=>{const P=Math.min(Math.max(Number(h)||t,z),b);s(Number(P.toFixed(2)))},c=Ee(bt(e,t),i),m=c?.contributionAvailable?ne(Number(c.proposed.marginPct)*100):"Pending",f=c?.contributionAvailable?ne(Number(e.foodCost?.cost)/Number(c.proposed.realizedUnitRevenue)*100):"Pending";
1return(0,r.jsxs)("div",{"data-testid":`srp-price-controls-${n}`,className:"mt-4 border-t border-zinc-200 pt-4",children:[(0,r.jsxs)("div",{className:"grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(300px,0.85fr)]",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{className:"text-base font-semibold text-zinc-950",children:a("srpStudio.tryPrice")}),(0,r.jsx)("p",{className:"mt-1 text-sm leading-6 text-zinc-600",children:a("srpStudio.startLevel",{step:W(p)})}),l.length?(0,r.jsx)("div",{className:"mt-3 grid gap-2 sm:grid-cols-3",children:l.map(h=>{const P=Math.abs(Number(h.price)-t)<.001;return(0,r.jsxs)("button",{type:"button","data-testid":`srp-tier-${h.id}-${n}`,"aria-pressed":P,onClick:()=>y(h.price),className:`min-h-[68px] rounded-lg border px-3 py-2 text-left focus:outline-none focus:ring-4 focus:ring-brand-500/20 ${P?"border-brand-600 bg-brand-50 text-brand-950":"border-zinc-200 bg-white text-zinc-800 hover:bg-zinc-50"}`,children:[(0,r.jsx)("span",{className:"block text-xs font-medium text-zinc-600",children:ur(h,a)}),(0,r.jsx)("span",{className:"mt-1 block text-base font-semibold",children:W(h.price)})]},h.id)})}):null,(0,r.jsxs)("div",{className:"mt-4 grid grid-cols-[44px_minmax(0,1fr)_44px] items-center gap-3",children:[(0,r.jsx)("button",{type:"button","aria-label":a("srpStudio.decreasePrice",{item:e.itemName}),onClick:()=>y(t-p),className:"h-11 w-11 rounded-lg border border-zinc-300 bg-white text-xl font-semibold text-zinc-800 focus:outline-none focus:ring-4 focus:ring-brand-500/20",children:"-"}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("label",{htmlFor:`srp-slider-${n}`,className:"flex items-center justify-between gap-3 text-sm font-medium text-zinc-700",children:[(0,r.jsx)("span",{children:a("srpStudio.price")}),(0,r.jsx)("output",{"data-testid":`srp-selected-price-${n}`,htmlFor:`srp-slider-${n}`,className:"font-semibold text-zinc-950","aria-live":"polite",children:W(t)})]}),(0,r.jsx)("input",{id:`srp-slider-${n}`,"data-testid":`srp-price-slider-${n}`,type:"range",min:z,max:b,step:p,value:t,"aria-valuetext":W(t)||"",onChange:h=>y(h.target.value),className:"h-11 w-full cursor-pointer accent-brand-700"})]}),(0,r.jsx)("button",{type:"button","aria-label":a("srpStudio.increasePrice",{item:e.itemName}),onClick:()=>y(t+p),className:"h-11 w-11 rounded-lg border border-zinc-300 bg-white text-xl font-semibold text-zinc-800 focus:outline-none focus:ring-4 focus:ring-brand-500/20",children:"+"})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{className:"text-base font-semibold text-zinc-950",children:i===0?a("srpStudio.atCurrentSales"):a("srpStudio.ifSalesLower",{drop:i})}),(0,r.jsxs)("div",{className:"mt-3 grid gap-2 sm:grid-cols-3 lg:grid-cols-1",children:[(0,r.jsx)(tt,{label:a("srpStudio.selectedPrice"),value:W(t),testId:`srp-preview-price-${n}`}),(0,r.jsx)(tt,{label:a("srpStudio.margin"),value:m,helper:c?.contributionAvailable?a("srpStudio.perItem",{value:W(c.proposed.unitContribution)}):a("srpStudio.pendingFoodCost"),testId:`srp-preview-margin-${n}`}),(0,r.jsx)(tt,{label:a("pricingStudio.foodCostPct"),value:f,helper:c?.contributionAvailable?a("srpStudio.verifiedRecipe"):a("srpStudio.pendingFoodCost"),testId:`srp-preview-food-cost-pct-${n}`})]})]})]}),(0,r.jsx)("div",{className:"mt-4 rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-4",children:c?.contributionAvailable?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"text-sm font-semibold text-emerald-950",children:a("srpStudio.grossContribution",{current:mt(c.current.weeklyContribution),proposed:mt(c.proposed.weeklyContribution)})}),(0,r.jsxs)("p",{"data-testid":`srp-simulator-contribution-${n}`,className:"mt-1 text-sm leading-6 text-emerald-900",children:[a("srpStudio.scenarioContribution",{change:te(c.weeklyContributionDelta)}),c.maxVolumeDropPct!=null?` ${a("srpStudio.breakeven",{percent:ne(c.maxVolumeDropPct)})}`:""]})]}):(0,r.jsx)("p",{className:"text-sm leading-6 text-zinc-700",children:a("srpStudio.projectedRevenue",{change:te(c?.weeklyRevenueDelta)})})}),(0,r.jsxs)("p",{className:"mt-3 text-sm leading-6 text-zinc-600",children:[a("srpStudio.toastBasis",{units:pt(e.weeklyUnits)}),e.realizedUnitRevenue!=null&&Math.abs(Number(e.realizedUnitRevenue)-Number(e.currentPrice))>=.01?` ${a("srpStudio.discountBasis",{value:W(e.realizedUnitRevenue)})}`:""]})]})},ji=({row:e,expanded:t,selectedPrice:s,onToggle:i,onPriceChange:a,volumeDropPct:n,t:o})=>{const l=ye(e),u=xi(e,s,n),p=u?.contributionAvailable?ne(Number(u.current.marginPct)*100):null,x=u?.contributionAvailable?ne(Number(u.proposed.marginPct)*100):null,d=e.rating==="under"?o("srpStudio.worthReviewing"):e.rating==="over"?o("srpStudio.watchDemand"):e.rating==="at"?o("srpStudio.looksAligned"):o("srpStudio.needsSales");return(0,r.jsx)("li",{children:(0,r.jsxs)("article",{"data-testid":`srp-market-card-${l}`,className:"border-t border-zinc-200 px-4 py-4 sm:px-5",children:[(0,r.jsxs)("div",{className:"grid gap-4 lg:grid-cols-[minmax(220px,2fr)_100px_110px_110px_150px_112px] lg:items-center",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{"data-testid":`srp-market-rating-${l}`,className:"text-xs font-semibold text-brand-700",children:d}),(0,r.jsx)("h3",{"data-testid":`srp-market-name-${l}`,className:"mt-1 text-base font-semibold text-zinc-950",children:e.itemName||o("srpStudio.unnamedItem")}),(0,r.jsx)("p",{"data-testid":`srp-market-impact-${l}`,className:"mt-1 text-sm leading-5 text-zinc-600",children:o("srpStudio.soldMix",{units:pt(e.weeklyUnits),mix:pt((Number(e.mixWeight)||0)*100)})}),(0,r.jsx)(gi,{row:e,t:o})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-xs text-zinc-600 lg:hidden",children:o("srpStudio.currentPrice")}),(0,r.jsx)("p",{"data-testid":`srp-market-current-${l}`,className:"mt-1 font-semibold text-zinc-950",children:W(e.currentPrice)||o("srpStudio.needsData")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-xs text-zinc-600 lg:hidden",children:o("srpStudio.suggestedPrice")}),(0,r.jsx)("p",{"data-testid":`srp-market-suggested-${l}`,className:"mt-1 text-lg font-semibold text-emerald-700",children:W(e.suggestedPrice)||o("srpStudio.needsData")}),(0,r.jsx)("p",{className:"mt-1 text-xs text-zinc-600",children:o("srpStudio.suggestionOnly")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-xs text-zinc-600 lg:hidden",children:o("srpStudio.margin")}),(0,r.jsx)("p",{"data-testid":`srp-margin-story-${l}`,className:"mt-1 text-sm font-semibold text-zinc-950",children:p&&x?o("srpStudio.marginChange",{current:p,proposed:x}):o("srpStudio.pendingCost")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-xs text-zinc-600 lg:hidden",children:o("srpStudio.contribution")}),(0,r.jsx)("p",{"data-testid":`srp-market-weekly-${l}`,className:"mt-1 font-semibold text-zinc-950",children:u?.contributionAvailable?o("srpStudio.perWeekValue",{value:te(u.weeklyContributionDelta)}):o("srpStudio.pendingCost")}),(0,r.jsx)("p",{"data-testid":`srp-market-monthly-${l}`,className:"mt-1 text-xs text-zinc-600",children:u?.contributionAvailable?o("srpStudio.perMonthValue",{value:te(u.weeklyContributionDelta*dr)}):o("srpStudio.revenueAvailable")})]}),(0,r.jsx)("button",{type:"button","data-testid":`srp-review-${l}`,"aria-expanded":t,onClick:i,className:"min-h-11 rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm font-semibold text-zinc-800 hover:bg-zinc-50 focus:outline-none focus:ring-4 focus:ring-brand-500/20",children:o(t?"srpStudio.close":"srpStudio.reviewPrice")})]}),t?(0,r.jsx)(Ni,{row:e,selectedPrice:s,onPriceChange:a,volumeDropPct:n,t:o}):null]})})},Si=({store:e,rows:t,rollup:s,volumeDropPct:i,onVolumeDropChange:a,t:n})=>{const o=t.find(b=>b.tierModel?.recommendedTier)?.tierModel||{},l=o.recommendedTier||{},u=o.tierReady===!0,p=u?ur(l,n):n("srpStudio.bestAvailable"),x=ne((Number(s.trustedCoveragePct)||0)*100),d=s.weeklyContributionDelta!=null,g=[u?n("srpStudio.comparableStores"):"",o.market?.census?.available?n("srpStudio.localIncome"):"",t[0]?.competitorContext?.status==="available"?n("srpStudio.nearbyContext"):""].filter(
1Boolean),z=t.find(b=>b?.marginAware?.targetMarginPct>0)?.marginAware?.targetMarginPct;return(0,r.jsxs)("section",{"data-testid":"srp-market-summary",className:"border-b border-zinc-200 pb-5",children:[(0,r.jsxs)("div",{className:"grid gap-5 lg:grid-cols-[minmax(0,1.4fr)_minmax(280px,0.6fr)] lg:items-start",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-sm font-semibold text-brand-700",children:e}),(0,r.jsx)("h2",{className:"mt-1 text-2xl font-semibold text-zinc-950",children:n("srpStudio.recommendedLevel",{level:p})}),(0,r.jsxs)("p",{className:"mt-2 max-w-3xl text-base leading-7 text-zinc-700",children:[n("srpStudio.builtFrom",{sources:g.length?g.join(", "):n("srpStudio.availableSales")}),` ${s.trustedItemCount>0?n("srpStudio.verifiedCostProtects"):n("srpStudio.costPendingSummary")}`]}),(0,r.jsx)("p",{className:"mt-2 text-sm font-medium text-zinc-700",children:n("srpStudio.suggestionDecision")}),z?(0,r.jsx)("p",{className:"mt-1 text-sm text-zinc-600",children:n("srpStudio.pricingTarget",{margin:ne(z*100)})}):null]}),(0,r.jsx)(bi,{value:i,onChange:a,t:n})]}),(0,r.jsxs)("div",{className:"mt-5 grid gap-3 sm:grid-cols-3",children:[(0,r.jsx)(et,{label:n("srpStudio.weeklyContribution"),value:d?te(s.weeklyContributionDelta):n("srpStudio.pendingCost"),helper:i===0?n("srpStudio.allCurrent"):n("srpStudio.allLower",{drop:i}),testId:"srp-store-weekly-contribution"}),(0,r.jsx)(et,{label:n("srpStudio.monthlyContribution"),value:d?te(s.weeklyContributionDelta*dr):n("srpStudio.pendingCost"),helper:n("srpStudio.notNetIncome"),testId:"srp-store-monthly-contribution"}),(0,r.jsx)(et,{label:n("srpStudio.costCoverage"),value:x||"0.0%",helper:n("srpStudio.trackedItems",{trusted:s.trustedItemCount||0,total:s.itemCount||0}),testId:"srp-store-cost-coverage"})]})]})},zi=({report:e,expectedStores:t=null,tenantName:s="MarginGains",loading:i=!1,error:a=""})=>{const{t:n,lang:o}=pr(),l=e&&Array.isArray(e.rows)?e.rows:[],u=e?.disclaimer||"",p=(0,w.useMemo)(()=>{const C={};return l.forEach(R=>{(C[R.store]=C[R.store]||[]).push(R)}),C},[l]),x=(0,w.useMemo)(()=>Array.isArray(t)&&t.length?[...t]:Object.keys(p).sort(),[t,p]),[d,g]=(0,w.useState)(()=>x[0]||""),[z,b]=(0,w.useState)(""),[y,c]=(0,w.useState)({}),[m,f]=(0,w.useState)(0);(0,w.useEffect)(()=>{x.includes(d)||g(x[0]||"")},[d,x]);const h=(0,w.useMemo)(()=>[...p[d]||[]].sort((C,R)=>Ot(R)-Ot(C)||String(C.itemName||"").localeCompare(String(R.itemName||""))),[d,p]),P=(0,w.useMemo)(()=>h.map(C=>bt(C,Number(y[ye(C)]??C.suggestedPrice??C.currentPrice))),[h,y]),I=(0,w.useMemo)(()=>sr({impacts:P,volumeDropPct:m}),[P,m]),M=e?.decisionSupport?.readiness?.byStore?.[d]||null,v=e?.decisionSupport?.menuBalance?.byStore?.[d]||null,j=e?.observedOutcomes?.byStore?.[d]||[],S=C=>{g(C),b("")};return(0,r.jsxs)("main",{"data-testid":"srp-market-module",className:"bg-zinc-50 px-4 py-5 text-zinc-950 sm:px-6",children:[(0,r.jsx)("header",{className:"border-b border-zinc-200 pb-5",children:(0,r.jsxs)("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-sm font-semibold text-brand-700",children:n("srpStudio.eyebrow")}),(0,r.jsx)("h1",{className:"mt-1 text-3xl font-semibold text-zinc-950",children:n("srpStudio.title")}),(0,r.jsx)("p",{className:"mt-2 max-w-3xl text-base leading-7 text-zinc-700",children:n("srpStudio.subtitle",{tenantName:s})})]}),x.length>1?(0,r.jsxs)("div",{className:"w-full sm:w-64",children:[(0,r.jsx)("label",{htmlFor:"srp-store-selector",className:"text-sm font-semibold text-zinc-800",children:n("srpStudio.store")}),(0,r.jsx)("select",{id:"srp-store-selector","data-testid":"srp-store-selector",value:d,onChange:C=>S(C.target.value),className:"mt-1 min-h-11 w-full rounded-lg border border-zinc-300 bg-white px-3 text-base text-zinc-950 focus:border-brand-600 focus:outline-none focus:ring-4 focus:ring-brand-500/20",children:x.map(C=>(0,r.jsx)("option",{value:C,children:C},C))})]}):null]})}),a?(0,r.jsx)("div",{role:"alert",className:"mt-5 rounded-lg border border-amber-300 bg-amber-50 px-4 py-3 text-sm text-amber-950",children:a}):null,i?(0,r.jsx)("div",{"aria-live":"polite",className:"mt-5 rounded-lg border border-zinc-200 bg-white p-6 text-sm text-zinc-700",children:n("srpStudio.loading")}):null,!i&&!x.length?(0,r.jsxs)("div",{"data-testid":"srp-market-empty",className:"mt-5 rounded-lg border border-zinc-200 bg-white p-6",children:[(0,r.jsx)("h2",{className:"text-base font-semibold text-zinc-950",children:n("srpStudio.noDataTitle")}),(0,r.jsx)("p",{className:"mt-1 text-sm leading-6 text-zinc-600",children:n("srpStudio.noDataHelper")})]}):null,!i&&x.length?(0,r.jsx)("section",{"data-testid":`srp-market-store-${d}`,className:"mt-5",children:h.length?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(Si,{store:d,rows:h,rollup:I,volumeDropPct:m,onVolumeDropChange:f,t:n}
1),(0,r.jsx)(fi,{readiness:M,t:n}),(0,r.jsx)(vi,{outcomes:j,t:n,lang:o}),(0,r.jsx)(hi,{row:h[0],t:n}),(0,r.jsx)(yi,{balance:v,t:n}),(0,r.jsxs)("section",{className:"overflow-hidden rounded-lg border border-zinc-200 bg-white",children:[(0,r.jsxs)("div",{className:"px-4 py-4 sm:px-5",children:[(0,r.jsx)("h2",{className:"text-lg font-semibold text-zinc-950",children:n("srpStudio.menuRecommendations")}),(0,r.jsx)("p",{className:"mt-1 text-sm leading-6 text-zinc-600",children:n("srpStudio.menuRecommendationsHelper")})]}),(0,r.jsxs)("div",{className:"hidden border-t border-zinc-200 bg-zinc-50 px-5 py-3 text-xs font-semibold text-zinc-600 lg:grid lg:grid-cols-[minmax(220px,2fr)_100px_110px_110px_150px_112px]",children:[(0,r.jsx)("span",{children:n("srpStudio.itemAndMix")}),(0,r.jsx)("span",{children:n("srpStudio.current")}),(0,r.jsx)("span",{children:n("srpStudio.suggested")}),(0,r.jsx)("span",{children:n("srpStudio.margin")}),(0,r.jsx)("span",{children:n("srpStudio.contribution")}),(0,r.jsx)("span",{children:n("srpStudio.review")})]}),(0,r.jsx)("ul",{children:h.map(C=>{const R=ye(C),N=Number(y[R]??C.suggestedPrice??C.currentPrice);return(0,r.jsx)(ji,{row:C,expanded:z===R,selectedPrice:N,volumeDropPct:m,t:n,onToggle:()=>b(k=>k===R?"":R),onPriceChange:k=>c(D=>({...D,[R]:k}))},R)})})]})]}):(0,r.jsx)("div",{"data-testid":"srp-market-empty",className:"rounded-lg border border-zinc-200 bg-white p-6",children:(0,r.jsxs)("div",{"data-testid":`srp-market-store-empty-${d}`,children:[(0,r.jsx)("h2",{className:"text-base font-semibold text-zinc-950",children:n("srpStudio.noStoreDataTitle",{store:d})}),(0,r.jsx)("p",{className:"mt-1 text-sm leading-6 text-zinc-600",children:n("srpStudio.noStoreDataHelper")})]})})}):null,(0,r.jsxs)("footer",{"data-testid":"srp-market-disclaimer",className:"mt-6 border-t border-zinc-200 pt-4 text-sm leading-6 text-zinc-600",children:[(0,r.jsx)("p",{children:u}),(0,r.jsx)("p",{className:"mt-2",children:n("srpStudio.legalDecision")}),(0,r.jsx)("p",{className:"mt-2",children:n("srpStudio.legalImpact")})]})]})},le=e=>String(e||"").trim().replace(/\s+/g," "),Ci=90,Pi=.03,Ii=Kt(Bt,"saveRecipeMenuPrice"),wi=(e="")=>{const t=le(e).toLowerCase();return!(!t||t.includes("no vendor price sheets yet")||t.includes("vendor price sheet rows are taking longer"))},$t=Object.freeze({neutral:"border-zinc-200 bg-white text-zinc-900 hover:border-zinc-300 hover:bg-zinc-50",success:"border-emerald-200 bg-emerald-50 text-emerald-950 hover:border-emerald-300 hover:bg-emerald-100/70",warning:"border-amber-200 bg-amber-50 text-amber-950 hover:border-amber-300 hover:bg-amber-100/70"}),Lt=Object.freeze({neutral:"border-zinc-200 bg-zinc-50 text-zinc-600",success:"border-emerald-200 bg-white text-emerald-700",warning:"border-amber-200 bg-white text-amber-700"}),Ft=Object.freeze({ready:"border-emerald-200 bg-emerald-50 text-emerald-700",needs_setup:"border-amber-200 bg-amber-50 text-amber-800",cost_data_building:"border-amber-200 bg-amber-50 text-amber-800"}),_=Object.freeze({allCategories:"All categories",atCurrentVolume:"At current volume",afterRecipeCost:"After recipe cost",backToLanding:"Back to landing",categoryRollups:"Category rollups",costDataStillBuilding:"Cost data still building",currentPrice:"Current price",newMargin:"New margin",newPrice:"New price",displayOnlyPreview:"Display-only preview. Nothing is sent to POS or published from this page.",finishRecipeCostingForSimulator:"Finish recipe costing before using this simulator",priceSimulator:"Price simulator",projectedAnnualImpact:"Projected annual impact",projectedMonthlyImpact:"Projected monthly impact",projectedWeeklyImpact:"Projected weekly impact",recipeCost:"Recipe cost",realWeeklyUnits:"Real weekly units sold",reviewPrice:"Review price",noTrustworthyReviews:"No trustworthy price reviews are ready yet. Finish recipe-cost links first.",scope:"Scope:",searchPlaceholder:"Search item, category, or store",suggestedDisplayPrice:"Suggested display price",volumeDropChecks:"Volume-drop checks",whatToDoNext:"What to do next",weeklyImpact:"Weekly impact"}),rt=e=>Number.isFinite(Number(e))&&Number(e)>0?Number(e).toFixed(2):"",Oe=e=>le(e).toLowerCase(),Mi=({item:e={},recipes:t=[]}={})=>{const s=e?.source||{},i=Oe(e?.recipeId||s?.recipeId),a=Oe(e?.recipeName||s?.recipeName||e?.itemName);return(Array.isArray(t)?t:[]).find(n=>i&&Oe(n?.id||n?.recipeId)===i||a&&Oe(n?.name)===a)||null},ki=({profile:e={},isOwner:t,isAdmin:s,isSuperAdmin:i})=>{const a=le(e?.role).toLowerCase();return t||s||i||a==="owner"||a==="admin"||a==="manager"},Ri=({action:e,onNavigate:t,setSelectedTileId:s})=>{if(e){if(e.moduleId){t(e.moduleId,e.context||null);return}e.tileId&&s(e.tileId)}},_i=({canSeeAllStores:e,storeOptions:t,selectedStore:s,lockedStore:i,onChange:a})=>e?(0,r.jsxs)("label",{className:"flex items-center gap-2 text-sm font-semibold text-zinc-700",children:["Store",(0,r.jsxs)("select",{"data-testid":"pricing-store-switcher",value:s,onChange:n=>a(n.target.value),className:"min-h-[44px] rounded-xl border border-zinc-200 bg-white px-3 text-base font-semibold text-zinc-950 shadow-sm focus:border-brand-500 focus:outline-none focus:ring-4 focus:ring-brand-500/15",children:[(0,r.jsx)("option",{value:"",children:"All stores"}),t.map(n=>(0,r.jsx)("option",{value:n,children:n},n))]})]}):(0,r.jsxs)("div",{"data-testid":"pricing-store-locked-chip",className:"inline-flex min-h-[44px] items-center gap-2 rounded-xl border border-zinc-200 bg-zinc-50 px-3 text-sm font-semibold text-zinc-800",children:[(0,r.jsx)(he,{name:"Lock",
1size:15,className:"text-zinc-500"}),"Store: ",i||"Assigned store"]}),Ei=({tile:e,active:t,onClick:s})=>(0,r.jsxs)("button",{type:"button","data-testid":`pricing-tile-${e.id}`,onClick:s,className:`min-h-[148px] rounded-2xl border p-4 text-left shadow-sm transition focus:outline-none focus:ring-4 focus:ring-brand-500/15 ${$t[e.tone]||$t.neutral} ${t?"ring-2 ring-brand-500/40":""}`,children:[(0,r.jsxs)("span",{className:"flex items-start justify-between gap-3",children:[(0,r.jsx)("span",{className:`inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border ${Lt[e.tone]||Lt.neutral}`,children:(0,r.jsx)(he,{name:e.icon||"Circle",size:20})}),(0,r.jsx)(he,{name:"ChevronRight",size:17,className:"mt-2 text-zinc-400"})]}),(0,r.jsx)("span",{className:"mt-4 block text-sm font-semibold text-zinc-600",children:e.label}),(0,r.jsx)("span",{className:"mt-1 block text-xl font-bold leading-tight text-zinc-950",children:e.value}),(0,r.jsx)("span",{className:"mt-2 block text-sm leading-5 text-zinc-600",children:e.detail}),(0,r.jsx)("span",{className:"mt-3 inline-flex min-h-[28px] items-center text-sm font-semibold text-zinc-950",children:e.actionLabel})]}),Ai=({search:e,onSearchChange:t,category:s,onCategoryChange:i,categories:a})=>(0,r.jsxs)("div",{className:"grid gap-3 sm:grid-cols-[minmax(0,1fr)_220px]",children:[(0,r.jsxs)("label",{className:"block text-sm font-semibold text-zinc-700",children:["Search",(0,r.jsx)("input",{"data-testid":"pricing-detail-search",value:e,onChange:n=>t(n.target.value),placeholder:_.searchPlaceholder,className:"mt-1 min-h-[44px] w-full rounded-xl border border-zinc-200 bg-white px-3 text-base text-zinc-950 shadow-sm focus:border-brand-500 focus:outline-none focus:ring-4 focus:ring-brand-500/15"})]}),(0,r.jsxs)("label",{className:"block text-sm font-semibold text-zinc-700",children:["Category",(0,r.jsxs)("select",{"data-testid":"pricing-detail-category-filter",value:s,onChange:n=>i(n.target.value),className:"mt-1 min-h-[44px] w-full rounded-xl border border-zinc-200 bg-white px-3 text-base text-zinc-950 shadow-sm focus:border-brand-500 focus:outline-none focus:ring-4 focus:ring-brand-500/15",children:[(0,r.jsx)("option",{value:"all",children:_.allCategories}),a.map(n=>(0,r.jsx)("option",{value:n,children:n},n))]})]})]}),xt=({status:e,label:t})=>(0,r.jsx)("span",{className:`inline-flex min-h-[28px] items-center rounded-full border px-2.5 text-xs font-semibold ${Ft[e]||Ft.needs_setup}`,children:t}),Ti=({rows:e,onReview:t})=>(0,r.jsxs)("div",{"data-testid":"pricing-detail-item-table",children:[(0,r.jsx)("div",{className:"hidden overflow-hidden rounded-2xl border border-zinc-200 md:block",children:(0,r.jsxs)("table",{className:"min-w-full divide-y divide-zinc-200 bg-white text-sm",children:[(0,r.jsx)("thead",{className:"bg-zinc-50 text-left text-xs font-semibold uppercase text-zinc-500",children:(0,r.jsxs)("tr",{children:[(0,r.jsx)("th",{className:"px-4 py-3",children:"Item"}),(0,r.jsx)("th",{className:"px-4 py-3",children:_.currentPrice}),(0,r.jsx)("th",{className:"px-4 py-3",children:_.suggestedDisplayPrice}),(0,r.jsx)("th",{className:"px-4 py-3",children:_.recipeCost}),(0,r.jsx)("th",{className:"px-4 py-3",children:"Margin"}),(0,r.jsx)("th",{className:"px-4 py-3",children:"Volume"}),(0,r.jsx)("th",{className:"px-4 py-3",children:_.weeklyImpact}),(0,r.jsx)("th",{className:"px-4 py-3",children:"Action"})]})}),(0,r.jsx)("tbody",{className:"divide-y divide-zinc-100",children:e.map(s=>(0,r.jsxs)("tr",{className:"align-top",children:[(0,r.jsxs)("td",{className:"px-4 py-3",children:[(0,r.jsx)("div",{className:"font-semibold text-zinc-950",children:s.itemName}),(0,r.jsx)("div",{className:"mt-1 text-xs text-zinc-500",children:[s.store,s.category].filter(Boolean).join(" | ")})]}),(0,r.jsx)("td",{className:"px-4 py-3 font-semibold text-zinc-900",children:T.money(s.currentPrice)}),(0,r.jsx)("td",{className:"px-4 py-3 font-semibold text-zinc-900",children:s.suggestedDisplayPrice==null?"Needs setup":T.money(s.suggestedDisplayPrice)}),(0,r.jsx)("td",{className:"px-4 py-3 text-zinc-700",children:s.recipeCost==null?"Needs setup":T.money(s.recipeCost)}),(0,r.jsx)("td",{className:"px-4 py-3 text-zinc-700",children:s.marginDollars==null?"Needs setup":`${T.money(s.marginDollars)} (${T.pct(s.marginPct)})`}),(0,r.jsxs)("td",{className:"px-4 py-3 text-zinc-700",children:[Number(s.volume||0).toLocaleStr
1ing("en-US")," weekly"]}),(0,r.jsx)("td",{className:"px-4 py-3 font-semibold text-zinc-900",children:T.signedCompactMoney(s.weeklyImpact)}),(0,r.jsx)("td",{className:"px-4 py-3",children:(0,r.jsx)("button",{type:"button",onClick:()=>t(s),className:"inline-flex min-h-[44px] items-center justify-center rounded-xl border border-zinc-200 bg-white px-3 text-sm font-semibold text-zinc-950 hover:bg-zinc-50 focus:outline-none focus:ring-4 focus:ring-brand-500/15",children:_.reviewPrice})})]},s.rowId))})]})}),(0,r.jsx)("div",{"data-testid":"pricing-detail-mobile-cards",className:"grid gap-3 md:hidden",children:e.map(s=>(0,r.jsxs)("article",{className:"rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm",children:[(0,r.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{className:"text-base font-bold text-zinc-950",children:s.itemName}),(0,r.jsx)("p",{className:"mt-1 text-sm text-zinc-500",children:[s.store,s.category].filter(Boolean).join(" | ")})]}),(0,r.jsx)(xt,{status:s.status,label:s.statusLabel})]}),(0,r.jsxs)("dl",{className:"mt-4 grid grid-cols-2 gap-3 text-sm",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{className:"text-zinc-500",children:_.currentPrice}),(0,r.jsx)("dd",{className:"font-semibold text-zinc-950",children:T.money(s.currentPrice)})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{className:"text-zinc-500",children:_.suggestedDisplayPrice}),(0,r.jsx)("dd",{className:"font-semibold text-zinc-950",children:s.suggestedDisplayPrice==null?"Needs setup":T.money(s.suggestedDisplayPrice)})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{className:"text-zinc-500",children:_.recipeCost}),(0,r.jsx)("dd",{className:"font-semibold text-zinc-950",children:s.recipeCost==null?"Needs setup":T.money(s.recipeCost)})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{className:"text-zinc-500",children:_.weeklyImpact}),(0,r.jsx)("dd",{className:"font-semibold text-zinc-950",children:T.signedCompactMoney(s.weeklyImpact)})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>t(s),className:"mt-4 inline-flex min-h-[44px] w-full items-center justify-center rounded-xl border border-zinc-200 bg-white px-3 text-sm font-semibold text-zinc-950 hover:bg-zinc-50 focus:outline-none focus:ring-4 focus:ring-brand-500/15",children:_.reviewPrice})]},s.rowId))})]}),Di=({rows:e})=>(0,r.jsxs)("div",{"data-testid":"pricing-cost-data-building-list",children:[(0,r.jsx)("div",{className:"hidden overflow-hidden rounded-2xl border border-amber-200 md:block",children:(0,r.jsxs)("table",{className:"min-w-full divide-y divide-amber-100 bg-white text-sm",children:[(0,r.jsx)("thead",{className:"bg-amber-50 text-left text-xs font-semibold uppercase text-amber-800",children:(0,r.jsxs)("tr",{children:[(0,r.jsx)("th",{className:"px-4 py-3",children:"Item"}),(0,r.jsx)("th",{className:"px-4 py-3",children:_.currentPrice}),(0,r.jsx)("th",{className:"px-4 py-3",children:_.recipeCost}),(0,r.jsx)("th",{className:"px-4 py-3",children:"Status"}),(0,r.jsx)("th",{className:"px-4 py-3",children:_.whatToDoNext})]})}),(0,r.jsx)("tbody",{className:"divide-y divide-amber-100",children:e.map(t=>(0,r.jsxs)("tr",{className:"align-top",children:[(0,r.jsxs)("td",{className:"px-4 py-3",children:[(0,r.jsx)("div",{className:"font-semibold text-zinc-950",children:t.itemName}),(0,r.jsx)("div",{className:"mt-1 text-xs text-zinc-500",children:[t.store,t.category].filter(Boolean).join(" | ")})]}),(0,r.jsx)("td",{className:"px-4 py-3 font-semibold text-zinc-900",children:T.money(t.currentPrice)}),(0,r.jsx)("td",{className:"px-4 py-3 text-zinc-700",children:t.recipeCost==null?"Still linking":T.money(t.recipeCost)}),(0,r.jsx)("td",{className:"px-4 py-3",children:(0,r.jsx)(xt,{status:t.status,label:t.statusLabel})}),(0,r.jsx)("td",{className:"px-4 py-3 text-zinc-700",children:t.reason})]},t.rowId))})]})}),(0,r.jsx)("div",{className:"grid gap-3 md:hidden",children:e.map(t=>(0,r.jsxs)("article",{className:"rounded-2xl border border-amber-200 bg-white p-4 shadow-sm",children:[(0,r.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{className:"text-base font-bold text-zinc-950",children:t.itemName}),(0,r.jsx)("p",{className:"mt-1 text-sm text-zinc-500",children:[t.store,t.category].filter(
1Boolean).join(" | ")})]}),(0,r.jsx)(xt,{status:t.status,label:t.statusLabel})]}),(0,r.jsxs)("dl",{className:"mt-4 grid grid-cols-2 gap-3 text-sm",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{className:"text-zinc-500",children:_.currentPrice}),(0,r.jsx)("dd",{className:"font-semibold text-zinc-950",children:T.money(t.currentPrice)})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{className:"text-zinc-500",children:_.recipeCost}),(0,r.jsx)("dd",{className:"font-semibold text-zinc-950",children:t.recipeCost==null?"Still linking":T.money(t.recipeCost)})]})]}),(0,r.jsx)("p",{className:"mt-4 text-sm leading-6 text-zinc-700",children:t.reason})]},t.rowId))})]}),Oi=({rows:e})=>e.length?(0,r.jsxs)("section",{className:"rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm","data-testid":"pricing-category-rollups",children:[(0,r.jsx)("h3",{className:"text-base font-bold text-zinc-950",children:_.categoryRollups}),(0,r.jsx)("div",{className:"mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:e.map(t=>(0,r.jsxs)("div",{className:"rounded-xl border border-zinc-200 bg-zinc-50 p-3",children:[(0,r.jsx)("div",{className:"text-sm font-semibold text-zinc-950",children:t.category}),(0,r.jsxs)("div",{className:"mt-2 text-sm text-zinc-600",children:[t.costedItemCount," of ",t.itemCount," costed / ",T.money(t.totalMarginDollars)," margin / ",T.pct(t.marginPct)]})]},t.category))})]}):null,$i=({recipe:e,item:t,storeOptions:s,selectedStore:i,canManage:a,onSavePrice:n})=>{const[o,l]=(0,w.useState)(e||null),[u,p]=(0,w.useState)(rt(e?.salePrice)),[x,d]=(0,w.useState)(""),[g,z]=(0,w.useState)(""),[b,y]=(0,w.useState)(""),c=o?.id===e?.id?o:e,m=le(i||t?.store),f=(0,w.useMemo)(()=>Pr(c||{}),[c]),h=(0,w.useMemo)(()=>{const j=new Set,S=[],C=R=>{const N=le(R),k=N.toLowerCase();!N||j.has(k)||(j.add(k),S.push(N))};return(Array.isArray(s)?s:[]).forEach(C),f.forEach(R=>C(R.store)),C(m),S},[f,m,s]),P=m?Qe(c||{},m):null,I=Qe(c||{},"All stores"),M=P?.source==="override";if((0,w.useEffect)(()=>
1{l(e||null),p(rt(e?.salePrice)),y("")},[e?.id,e?.salePrice]),(0,w.useEffect)(()=>{d(rt(P?.overridePrice))},[e?.id,m,P?.overridePrice]),!t)return null;if(!c?.id)return(0,r.jsxs)("section",{"data-testid":"pricing-price-setter",className:"mt-4 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm leading-6 text-amber-900",children:[(0,r.jsx)("p",{className:"font-bold",children:"Set menu price"}),(0,r.jsx)("p",{className:"mt-1",children:"This sold item is not linked to a recipe record yet. Link it in Recipe Book before saving a menu price."})]});const v=async({action:j,clearStoreOverride:S=!1}={})=>{if(!a||g)return;const C=Number(u);if(!Number.isFinite(C)||C<=0){y("Enter an all-store default price before saving.");return}if(j==="override"&&!S){const R=Number(x);if(!m){y("Choose a store before saving a store override.");return}if(!Number.isFinite(R)||R<=0){y(`Enter a ${m} override price before saving.`);return}}if(j==="clear"&&!m){y("Choose a store before clearing an override.");return}z(j||"default"),y("");try{const R=await n({recipe:c,item:t,allStorePrice:u,selectedStore:m,storePrice:x,clearStoreOverride:S});l(N=>({...N||c,...R})),S?(d(""),y(`Cleared ${m} override. It now uses the all-store default.`)):y(j==="override"?`Saved ${m} override for ${c.name||t.itemName}.`:`Saved all-store default for ${c.name||t.itemName}.`)}catch(R){y(`Error: ${gr(R,"Could not save this recipe price")}`)}z("")};return(0,r.jsxs)("section",{"data-testid":"pricing-price-setter",className:"mt-4 rounded-2xl border border-zinc-200 bg-zinc-50 p-4",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-sm font-bold text-zinc-950",children:"Set menu price"}),(0,r.jsx)("p",{className:"mt-1 text-sm leading-5 text-zinc-600",children:"Saves to Recipe Book: all-store default first, then store override when needed."})]}),(0,r.jsxs)("span",{className:"inline-flex min-h-[28px] items-center rounded-full border border-zinc-200 bg-white px-3 text-xs font-semibold text-zinc-700",children:["Current: ",I.resolvedPrice==null?"Not set":T.money(I.resolvedPrice)]})]}),(0,r.jsxs)("div",{className:"mt-4 grid gap-3 lg:grid-cols-2",children:[(0,r.jsxs)("label",{className:"block text-sm font-semibold text-zinc-700",children:["All-store default price",(0,r.jsxs)("div",{className:"mt-1 flex min-h-[48px] items-center rounded-xl border border-zinc-200 bg-white px-3 shadow-sm focus-within:border-brand-500 focus-within:ring-4 focus-within:ring-brand-500/15",children:[(0,r.jsx)("span",{className:"font-bold text-zinc-500",children:"$"}),(0,r.jsx)("input",{type:"number",inputMode:"decimal",min:"0",step:"0.01","data-testid":"pricing-all-store-price-input",value:u,onChange:j=>p(j.target.value),disabled:!a,className:"min-h-[44px] w-full border-0 bg-transparent px-2 text-base font-semibold text-zinc-950 outline-none disabled:text-zinc-400","aria-label":`All-store default price for ${c.name||t.itemName}`})]}),(0,r.jsx)("span",{className:"mt-1 block text-xs text-zinc-500",children:"Applies to every store unless that store has an override."})]}),(0,r.jsxs)("div",{className:"rounded-xl border border-zinc-200 bg-white p-3",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-sm font-semibold text-zinc-900",children:m?`${m} override`:"Store override"}),(0,r.jsx)("p",{className:"text-xs text-zinc-500",children:m?"This store wins over the all-store default.":"Choose a store at the top to set an override."})]}),P?(0,r.jsx)("span",{className:`inline-flex min-h-[26px] items-center rounded-full px-2.5 text-xs font-semibold ${P.source==="override"?"bg-blue-100 text-blue-700":"bg-zinc-100 text-zinc-600"}`,children:P.sourceLabel}):null]}),(0,r.jsxs)("div",{className:"mt-3 flex min-h-[48px] items-center rounded-xl border border-zinc-200 bg-zinc-50 px-3 focus-within:border-brand-500 focus-within:ring-4 focus-within:ring-brand-500/15",children:[(0,r.jsx)("span",{className:"font-bold text-zinc-500",children:"$"}),(0,r.jsx)("input",{type:"number",inputMode:"decimal",min:"0",step:"0.01","data-testid":"pricing-store-override-input",value:x,onChange:j=>d(j.target.value),disabled:!a||!m,placeholder:m?"Use all-store default":"Select a store first",className:"min-h-[44px] w-full border-0 bg-transparent px-2 text-base font-semibold text-zinc-950 outline-none disabled:text-zinc-400","aria-label":m?`${m} override price for ${c.name||t.itemName}`:"Selected store override price"})]})]})]}),a?(0,r.jsxs)("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[(0,r.jsx)("button",{type:"button","data-testid":"pricing-save-all-store-price",onClick:()=>v({action:"default"}),disabled:!!g,className:"inline-flex min-h-[44px] items-center justify-center rounded-xl bg-zinc-950 px-4 text-sm font-semibold text-white hover:bg-zinc-800 focus:outline-none focus:ring-4 focus:ring-brand-500/15 disabled:cursor-not-allowed disabled:bg-zinc-300",children:g==="default"?"Saving...":"Save all-store default"}),(0,r.jsx)("button",{type:"button","data-testid":"pricing-save-store-override",onClick:()=>v({action:"override"}),disabled:!!g||!m,className:"inline-flex min-h-[44px] items-center justify-center rounded-xl border border-zinc-200 bg-white px-4 text-sm font-semibold text-zinc-950 hover:bg-zinc-50 focus:outline-none focus:ring-4 focus:ring-brand-500/15 disabled:cursor-not-allowed disabled:text-zinc-400",children:g==="override"?"Saving...":"Save store override"}),M?(0,r.jsx)("button",{type:"button","data-testid":"pricing-clear-store-override",onClick:()=>v({action:"clear",clearStoreOverride:!0}),disabled:!!g,className:"inline-flex min-h-[44px] items-center justify-center rounded-xl border border-red-200 bg-white px-4 text-sm font-semibold text-red-700 hover:bg-red-50 focus:outline-none focus:ring-4 focus:ring-red-500/15 disabled:cursor-not-allowed disabled:text-zinc-400",children:g==="clear"?"Clearing...":"Clear store override"}):null]}):(0,r.jsx)("p",{className:"mt-3 rounded-xl border border-zinc-200 bg-white px-3 py-2 text-sm text-zinc-600",children:"Only owner, admin, and manager roles can save recipe prices."}),b?(0,r.jsx)("p",{"data-testid":"pricing-price-save-status",className:"mt-3 rounded-xl border border-zinc-200 bg-white px-3 py-2 text-sm font-semibold text-zinc-700",children:b}):null,(0,r.jsx)("div",{className:"mt-4 overflow-hidden rounded-xl border border-zinc-200 bg-white",children:(0,r.jsxs)("table",{className:"min-w-full divide-y divide-zinc-100 text-sm",children:[(0,r.jsx)("thead",{className:"bg-zinc-50 text-left text-xs font-semibold uppercase text-zinc-500",children:(0,r.jsxs)("tr",{children:[(0,r.jsx)("th",{className:"px-3 py-2",children:"Store"}),(0,r.jsx)("th",{className:"px-3 py-2",children:"Resolved price"}),(0,r.jsx)("th",{className:"px-3 py-2",children:"In effect"})]})}),(0,r.jsx)("tbody",{className:"divide-y divide-zinc-100",children:h.length?h.map(j=>{const S=Qe(c||{},j);return(0,r.jsxs)("tr",{"data-testid":`pricing-resolved-store-${S.key||j}`,children:[(0,r.jsx)("td",{className:"px-3 py-2 font-semibold text-zinc-900",children:j}),(0,r.jsx)("td",{className:"px-3 py-2 text-zinc-700",children:S.resolvedPrice==null?"Not set":T.money(S.resolvedPrice)}),(0,r.jsx)("td",{className:"px-3 py-2 text-zinc-700",children:S.sourceLabel})]},j)}):(0,r.jsxs)("tr",{children:[(0,r.jsx)("td",{className:"px-3 py-2 font-semibold text-zinc-900",children:"All stores"}),(0,r.jsx)("td",{className:"px-3 py-2 text-zinc-700",children:I.resolvedPrice==null?"Not set":T.money(I.resolvedPrice)}),(0,r.jsx)("td",{className:"px-3 py-2 text-zinc-700",children:I.sourceLabel})]})})]})})]})},Li=({item:e,recipe:t,storeOptions:s,selectedStore:i,canManagePrices:a,onSavePrice:n})=>{const o=Number(e?.currentPrice??e?.price??e?.source?.price),l=Number.isFinite(o)&&o>0?o.toFixed(2):"",[u,p]=(0,w.useState)(l);if((0,w.useEffect)(()=>{p(l)},[l,e?.rowId]),!e)return null;const x=Number(u),d=Number.isFinite(x)&&x>0?x:null,g=Cr({item:e,newPrice:d}),z=Number.isFinite(o)&&o>0?Math.max(0,Math.floor((o-5)*100)/100):0,b=Number.isFinite(o)&&o>0?Math.ceil(Math.max(o+5,o*1.5,5)*100)/100:25,y=Number.isFinite(d)?Math.min(Math.max(d,z),b):Number.isFinite(o)&&o>0?o:z,c=g.blocked||!(Number.isFinite(o)&&o>0),m=h=>{!Number.isFinite(o)||o<=0||p((o+h).toFixed(2))},f=`${_.finishRecipeCostingForSimulator} for ${e.itemName}.`;return(0,r.jsxs)("aside",{"data-testid":"pricing-simulator",className:"rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("p",{className:"text-sm font-semibold text-zinc-500",children:_.priceSimulator}),(0,r.jsx)("h3",{className:"mt-1 text-lg font-bold text-zinc-950",children:e.itemName}),(0,r.jsx)("p",{className:"mt-1 text-sm leading-5 text-zinc-600",children:_.displayOnlyPreview})]}),(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-none sm:justify-items-end",children:[(0,r.jsx)("button",{type:"button","data-testid":"pricing-simulator-plus-25",onClick:()=>
1m(.25),disabled:c,className:"inline-flex min-h-[44px] items-center justify-center rounded-xl bg-zinc-950 px-4 text-sm font-semibold text-white hover:bg-zinc-800 focus:outline-none focus:ring-4 focus:ring-brand-500/15 disabled:cursor-not-allowed disabled:bg-zinc-300",children:"+$0.25"}),(0,r.jsx)("button",{type:"button","data-testid":"pricing-simulator-plus-1",onClick:()=>m(1),disabled:c,className:"inline-flex min-h-[44px] items-center justify-center rounded-xl border border-zinc-200 bg-white px-4 text-sm font-semibold text-zinc-950 hover:bg-zinc-50 focus:outline-none focus:ring-4 focus:ring-brand-500/15 disabled:cursor-not-allowed disabled:text-zinc-400",children:"+$1"})]})]}),(0,r.jsxs)("div",{className:"mt-4 grid gap-3 sm:grid-cols-3",children:[(0,r.jsxs)("div",{className:"rounded-xl border border-zinc-200 bg-zinc-50 p-3",children:[(0,r.jsx)("div",{className:"text-xs font-semibold uppercase text-zinc-500",children:_.currentPrice}),(0,r.jsx)("div",{"data-testid":"pricing-simulator-current-price",className:"mt-1 text-lg font-bold text-zinc-950",children:g.currentPriceLabel})]}),(0,r.jsxs)("div",{className:"rounded-xl border border-zinc-200 bg-zinc-50 p-3",children:[(0,r.jsx)("div",{className:"text-xs font-semibold uppercase text-zinc-500",children:_.recipeCost}),(0,r.jsx)("div",{"data-testid":"pricing-simulator-recipe-cost",className:"mt-1 text-lg font-bold text-zinc-950",children:g.recipeCostLabel})]}),(0,r.jsxs)("div",{className:"rounded-xl border border-zinc-200 bg-zinc-50 p-3",children:[(0,r.jsx)("div",{className:"text-xs font-semibold uppercase text-zinc-500",children:_.realWeeklyUnits}),(0,r.jsx)("div",{"data-testid":"pricing-simulator-weekly-units",className:"mt-1 text-lg font-bold text-zinc-950",children:g.weeklyUnitsLabel})]})]}),g.blocked?(0,r.jsxs)("div",{"data-testid":"pricing-simulator-blocked",className:"mt-4 rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm leading-6 text-amber-900",children:[(0,r.jsx)("p",{className:"font-bold",children:_.costDataStillBuilding}),(0,r.jsx)("p",{className:"mt-1",children:f})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("label",{className:"mt-4 block text-sm font-semibold text-zinc-700",children:[_.newPrice,(0,r.jsxs)("div",{className:"mt-1 flex min-h-[56px] items-center rounded-2xl border border-zinc-200 bg-white px-4 shadow-sm focus-within:border-brand-500 focus-within:ring-4 focus-within:ring-brand-500/15",children:[(0,r.jsx)("span",{className:"text-xl font-bold text-zinc-500",children:"$"}),(0,r.jsx)("input",{type:"number",inputMode:"decimal",min:"0",step:"0.01","data-testid":"pricing-simulator-price-input",value:u,onChange:h=>p(h.target.value),className:"min-h-[52px] w-full border-0 bg-transparent px-2 text-2xl font-bold text-zinc-950 outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none","aria-label":`New price for ${e.itemName}`})]})]}),(0,r.jsxs)("div",{className:"mt-3",children:[(0,r.jsx)("input",{type:"range","data-testid":"pricing-simulator-price-slider",min:z,max:b,step:"0.25",value:y,disabled:c,onChange:h=>p(Number(h.target.value).toFixed(2)),className:"h-11 w-full accent-zinc-950 disabled:opacity-50","aria-label":`Slide new price for ${e.itemName}`}),(0,r.jsxs)("div",{className:"flex justify-between text-xs font-semibold text-zinc-500",children:[(0,r.jsx)("span",{children:T.money(z)}),(0,r.jsx)("span",{children:T.money(b)})]})]}),(0,r.jsxs)("div",{className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[(0,r.jsxs)("div",{className:"rounded-xl border border-zinc-200 bg-zinc-50 p-3",children:[(0,r.jsx)("div",{className:"text-xs font-semibold uppercase text-zinc-500",children:_.newPrice}),(0,r.jsx)("div",{"data-testid":"pricing-simulator-target-price",className:"mt-1 text-xl font-bold text-zinc-950",children:g.targetPriceLabel}),(0,r.jsxs)("div",{className:"mt-1 text-xs text-zinc-500",children:[g.priceDeltaLabel," per item"]})]}),(0,r.jsxs)("div",{className:"rounded-xl border border-zinc-200 bg-zinc-50 p-3",children:[(0,r.jsx)("div",{className:"text-xs font-semibold uppercase text-zinc-500",children:_.newMargin}),(0,r.jsxs)("div",{"data-testid":"pricing-simulator-new-margin",className:"mt-1 text-xl font-bold text-zinc-950",children:[g.newMarginDollarsLabel," / ",g.newMarginPctLabel]}),(0,r.jsx)("div",{className:"mt-1 text-xs text-zinc-500",children:_.afterRecipeCost})]}),(0,r.jsxs)("div",{className:"rounded-xl border border-zinc-200 bg-zinc-50 p-3",children:[(0,r.jsx)("div",{className:"text-xs font-semibold uppercase text-zinc-500",children:_.projectedWeeklyImpact}),(0,r.jsx)("div",{"data-testid":"pricing-simulator-weekly-impact",className:"mt-1 text-xl font-bold text-zinc-950",children:g.projectedWeeklyImpactLabel}),(0,r.jsx)("div",{className:"mt-1 text-xs text-zinc-500",children:_.at
1CurrentVolume})]}),(0,r.jsxs)("div",{className:"rounded-xl border border-zinc-200 bg-zinc-50 p-3",children:[(0,r.jsx)("div",{className:"text-xs font-semibold uppercase text-zinc-500",children:_.projectedAnnualImpact}),(0,r.jsx)("div",{"data-testid":"pricing-simulator-annual-impact",className:"mt-1 text-xl font-bold text-zinc-950",children:g.projectedAnnualImpactLabel}),(0,r.jsxs)("div",{className:"mt-1 text-xs text-zinc-500",children:[g.projectedMonthlyImpactLabel,"/month"]})]})]}),(0,r.jsx)("div",{"data-testid":"pricing-simulator-formula",className:"mt-3 rounded-xl border border-sky-200 bg-sky-50 p-3 text-sm leading-6 text-sky-950",children:g.formulaCopy||g.setupCopy}),g.sensitivity.length?(0,r.jsxs)("div",{className:"mt-3 rounded-xl border border-zinc-200 bg-zinc-50 p-3",children:[(0,r.jsx)("div",{className:"text-xs font-semibold uppercase text-zinc-500",children:_.volumeDropChecks}),(0,r.jsx)("div",{className:"mt-1 space-y-1 text-sm font-semibold text-zinc-900",children:g.sensitivity.map(h=>(0,r.jsxs)("div",{children:["Volume down ",h.dropPct,"%: ",T.signedCompactMoney(h.profitDelta)]},h.dropPct))})]}):null]}),(0,r.jsx)("p",{className:"mt-3 text-xs font-semibold text-zinc-500",children:g.disclaimer}),g.ready?null:(0,r.jsx)("p",{className:"mt-2 text-sm text-amber-700",children:g.setupCopy}),w.createElement($i,{recipe:t,item:e,storeOptions:s,selectedStore:i,canManage:a,onSavePrice:n})]})},Fi=({copy:e})=>(0,r.jsx)("div",{className:"rounded-2xl border border-dashed border-zinc-200 bg-zinc-50 p-5 text-sm text-zinc-600",children:e}),Ui=({item:e,onSelectStore:t})=>(0,r.jsxs)("article",{className:"rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{className:"text-base font-bold text-zinc-950",children:e.itemName}),(0,r.jsxs)("p",{className:"mt-1 text-sm text-zinc-600",children:[e.storeCount," stores / ",T.money(e.priceSpreadDollars)," price spread / ",T.pct(e.marginSpreadPct)," margin spread"]})]}),(0,r.jsxs)("span",{className:"inline-flex min-h-[28px] items-center rounded-full border border-amber-200 bg-amber-50 px-3 text-xs font-semibold text-amber-800",children:[e.outlierCount," store edges"]})]}),(0,r.jsx)("div",{className:"mt-4 grid gap-2 sm:grid-cols-2 lg:grid-cols-3",children:e.stores.map(s=>(0,r.jsxs)("button",{type:"button",onClick:()=>t(s.store),className:"min-h-[44px] rounded-xl border border-zinc-200 bg-zinc-50 p-3 text-left hover:bg-white focus:outline-none focus:ring-4 focus:ring-brand-500/15",children:[(0,r.jsxs)("span",{className:"block text-sm font-bold text-zinc-950",children:["Store: ",s.store]}),(0,r.jsxs)("span",{className:"mt-1 block text-sm text-zinc-600",children:[T.money(s.price)," / ",T.money(s.unitCost)," recipe cost / ",T.pct(s.marginPct)]}),s.outlierReason?(0,r.jsx)("span",{className:"mt-1 block text-xs font-semibold text-amber-700",children:s.outlierReason}):null]},s.store))})]}),Bi=({detail:e,onSelectStore:t})=>(0,r.jsx)("div",{"data-testid":"pricing-store-outlier-detail",className:"space-y-3",children:e.comparisons.length?e.comparisons.map(s=>(0,r.jsx)(Ui,{item:s,onSelectStore:t},s.comparisonId)):(0,r.jsx)(Fi,{copy:e.emptyCopy})}),Ut=e=>e==="cost_data_building"||e==="needs_setup",Ki=({costDataDetail:e,selectedItem:t,rows:s,recipe:i,storeOptions:a,selectedStore:n,
1canManagePrices:o,onSavePrice:l})=>e?null:w.createElement(Li,{item:t||s.find(u=>u.status==="ready"),recipe:i,storeOptions:a,selectedStore:n,canManagePrices:o,onSavePrice:l}),Vi=({detail:e,selectedItem:t,onSelectItem:s,onBack:i,onSearchChange:a,onCategoryChange:n,onSelectStore:o,recipe:l,storeOptions:u,selectedStore:p,canManagePrices:x,onSavePrice:d})=>(0,r.jsxs)("section",{"data-testid":"pricing-detail-panel",className:"space-y-4 rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[(0,r.jsxs)("div",{children:[(0,r.jsxs)("p",{className:"text-sm font-semibold text-zinc-500",children:[_.scope," ",(0,r.jsx)("span",{className:"text-zinc-800",children:e.scopeLabel})]}),(0,r.jsx)("h2",{className:"mt-1 text-xl font-bold text-zinc-950",children:e.title}),(0,r.jsx)("p",{className:"mt-1 text-sm leading-6 text-zinc-600",children:e.summary})]}),(0,r.jsxs)("button",{type:"button",onClick:i,className:"inline-flex min-h-[44px] items-center justify-center rounded-xl border border-zinc-200 bg-white px-4 text-sm font-semibold text-zinc-950 hover:bg-zinc-50 focus:outline-none focus:ring-4 focus:ring-brand-500/15",children:[(0,r.jsx)(he,{name:"ArrowLeft",size:16}),_.backToLanding]})]}),(0,r.jsx)(Ai,{search:e.search,onSearchChange:a,category:e.category,onCategoryChange:n,categories:e.categoryOptions}),e.type==="store_outliers"?(0,r.jsx)(Bi,{detail:e,onSelectStore:o}):(0,r.jsxs)(r.Fragment,{children:[e.itemRows.length?Ut(e.type)?(0,r.jsx)(Di,{rows:e.itemRows}):(0,r.jsx)(Ti,{rows:e.itemRows,onReview:s}):(0,r.jsx)("div",{className:"rounded-2xl border border-dashed border-zinc-200 bg-zinc-50 p-5 text-sm text-zinc-600",children:e.emptyCopy}),(0,r.jsx)(Ki,{costDataDetail:Ut(e.type),selectedItem:t,rows:e.itemRows,recipe:l,storeOptions:u,selectedStore:p,canManagePrices:x,onSavePrice:d}),(0,r.jsx)(Oi,{rows:e.categoryRollups})]})]}),Wi=({model:e,onPrimary:t})=>e.setup.title?(0,r.jsx)("section",{"data-testid":"pricing-setup-state",className:"rounded-2xl border border-amber-200 bg-amber-50 p-4 text-amber-950",children:(0,r.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h2",{className:"text-base font-bold",children:e.setup.title}),(0,r.jsx)("p",{className:"mt-1 text-sm leading-6 text-amber-800",children:e.setup.detail})]}),(0,r.jsx)(Vt,{onClick:t,className:"min-h-[44px] bg-zinc-950 text-white hover:bg-zinc-800",children:e.primaryAction.label})]})}):null,qi=({opportunities:e})=>(0,r.jsxs)("section",{"data-testid":"pricing-top-opportunities",className:"rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm",children:[(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("h2",{className:"text-base font-bold text-zinc-950",children:"Top opportunities"}),(0,r.jsx)("p",{className:"mt-1 text-sm text-zinc-600",children:"Start with the few items most worth a closer look."})]}),(0,r.jsxs)("span",{className:"rounded-full border border-zinc-200 bg-zinc-50 px-3 py-1 text-xs font-semibold text-zinc-600",children:["Top ",Math.max(0,Math.min(5,e.length))]})]}),e.length?(0,r.jsx)("div",{className:"mt-4 grid gap-3",children:e.map(t=>(0,r.jsxs)("button",{type:"button",className:"min-h-[64px] rounded-xl border border-zinc-200 bg-zinc-50 px-4 py-3 text-left hover:bg-white focus:outline-none focus:ring-4 focus:ring-brand-500/15",children:[(0,r.jsx)("span",{className:"block text-sm font-semibold text-zinc-950",children:t.title}),(0,r.jsx)("span",{className:"mt-1 block text-sm leading-5 text-zinc-600",children:t.detail}),t.meta?(0,r.jsx)("span",{className:"mt-1 block text-xs text-zinc-500",children:t.meta}):null]},t.id||t.title))}):(0,r.jsx)("div",{className:"mt-4 rounded-xl border border-dashed border-zinc-200 bg-zinc-50 px-4 py-5 text-sm text-zinc-600",children:_.noTrustworthyReviews})]}),Gi=({enabled:e,tenantId:t,tenant:s,foodCostSources:i,foodCostError:a})=>{const{productMixDocs:n,recipes:o,stores:l,storeZip:u,loading:p,error:x}=li({tenantId:e?t:"",tenant:s}),{competitorContextByStoreItem:d}=si({tenantId:e?t:"",stores:l}),{zipTable:g}=di({enabled:e,zips:(0,w.useMemo)(()=>Object.values(u||{}),[u])}),z=(0,w.useMemo)(()=>{const b=Date.now(),y=as({foundation:qt(i)}),c=Qs(o||[]),m=Er({productMixDocs:n||[],windowDays:Ci,asOf:b,resolveName:c,isExcluded:Dt}),f=Rs({baseline:m,demographics:Or({stores:m.stores,storeZip:u,zipTable:g}),guardrails:Je.guardrails,atMarketPct:Pi,targetFoodCostPct:Je.costTargets?.foodCostPct,foodCostByRecipeId:y.byRecipeId,foodCostByItemKey:y.byItemKey,competitorContextByStoreItem:d,tierReferenceStores:s?.settings?.srp?.referenceStores||{},tierConfig:s?.settings?.srp?.tierModel||{},disclaimer:Je.disclaimer}),h=$s({rows:f.rows,storeCoverage:m.storeCoverage,asOf:b}),P=Us({productMixDocs:n||[],reportRows:f.rows,resolveName:c,isExcluded:Dt});return{...f,decisionSupport:h,observedOutcomes:P}},[d,i,n,o,u,s,g]);return e?(0,r.jsx)("section",{"data-testid":"pricing-srp-market-section",className:"border-y border-zinc-200 bg-zinc-50",children:(0,r.jsx)(zi,{report:z,expectedStores:l,tenantName:s?.name||s?.tenantName||"MarginGains",loading:p,error:x||a})}):null};function nn({user:e=null,profile:t={},tenant:s={},userStore:i="",canSeeAllStores:a=!1,isOwner:n=!1,isAdmin:o=!1,isCorporate:l=!1,isSuperAdmin:u=!1,onNavigate:p=()=>{}}){const x=le(s?.tenantId||s?.id||t?.tenantId||""),d=Sr({tenant:s}),g=kr({tenantId:x,tenant:s||{},profile:t||{}}),z=d||g,[b,y]=(0,w.useState)(""),[c,m]=(0,w.useState)(""),[f,h]=(0,w.useState)(""),[P,I]=(0,w.useState)("all"),[M,v]=(0,w.useState)(""),j=a===!0||n||o||l||u,S=le(i||t?.store||t?.primaryStore||t?.assignedStore),C=j?b
1:S,{sources:R,loading:N,error:k}=Rr({tenantId:z?x:"",tenant:s}),D=(0,w.useMemo)(()=>Ir({tenant:s,sources:R,fallbackStore:S}),[S,R,s]);(0,w.useEffect)(()=>{!j&&b&&y("")},[j,b]),(0,w.useEffect)(()=>{b&&(D.includes(b)||y(""))},[b,D]),(0,w.useEffect)(()=>{h(""),I("all"),v("")},[C]);const F=(0,w.useMemo)(()=>C?zr(R,C):R,[C,R]),L=(0,w.useMemo)(()=>{const A=qt(F);return Mr({productMixDocs:F.productMixDocs,recipes:F.recipes,recipeCostRows:A.rows,tenantId:x,store:C,scopeLabel:C||"All stores",canSeeAllStores:j})},[F,C,j,x]),G=(0,w.useMemo)(()=>c?wr({breakdown:L.breakdown,tileId:c,search:f,category:P,canSeeAllStores:j,scopeLabel:L.scope.label,store:C}):null,[C,j,P,f,L.breakdown,L.scope.label,c]),ce=(0,w.useMemo)(()=>G?.itemRows?.length?G.itemRows.find(A=>A.rowId===M)||G.itemRows.find(A=>A.status==="ready")||G.itemRows[0]:null,[G,M]),K=(0,w.useMemo)(()=>Mi({item:ce,recipes:F.recipes}),[F.recipes,ce]),Ne=ki({profile:t,isOwner:n,isAdmin:o,isSuperAdmin:u}),je=(0,w.useMemo)(()=>j?D:C?[C]:[],[C,j,D]),de=(0,w.useCallback)(async({recipe:A,allStorePrice:We,selectedStore:qe,storePrice:Ge,clearStoreOverride:He})=>{if(!Ne)throw new Error("You do not have permission to save recipe prices.");if(!A?.id)throw new Error("No linked recipe found for this sold item.");const ht=(await Ii({recipeId:A.id,allStorePrice:We,selectedStore:qe,storePrice:Ge,clearStoreOverride:He===!0}
1))?.data?.recipe||{};return{salePrice:ht.salePrice,priceOverridesByStore:ht.priceOverridesByStore||{}}},[Ne]);if(!e||!z)return null;const H=A=>Ri({action:A,onNavigate:p,setSelectedTileId:m}),Se=()=>H(L.primaryAction),ze=A=>{h(""),I("all"),v(""),m(A.id),A.moduleId&&p(A.moduleId,A.context||null)},Ae=A=>{y(A),m("top_reviews"),h(""),I("all"),v("")},ue=wi(k);return(0,r.jsx)("section",{"data-testid":"pricing-module",className:"min-h-[calc(100vh-120px)] rounded-[24px] border border-zinc-200 bg-zinc-50 text-zinc-950 shadow-sm",children:(0,r.jsxs)("div",{className:"mx-auto flex max-w-6xl flex-col gap-5 px-4 py-5 sm:px-6",children:[d?(0,r.jsxs)("header",{className:"rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[(0,r.jsx)("div",{className:"min-w-0",children:(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("span",{className:"inline-flex h-11 w-11 items-center justify-center rounded-xl bg-zinc-950 text-white",children:(0,r.jsx)(he,{name:"BadgeDollarSign",size:22})}),(0,r.jsxs)("div",{children:[(0,r.jsx)("h1",{className:"text-2xl font-bold tracking-tight text-zinc-950",children:"Pricing"}),(0,r.jsx)("p",{"data-testid":"pricing-answer-line",className:"mt-1 text-base leading-6 text-zinc-600",children:L.answer})]})]})}),(0,r.jsx)(_i,{canSeeAllStores:j,storeOptions:D,selectedStore:b,lockedStore:S,onChange:y})]}),(0,r.jsxs)("div",{className:"mt-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[(0,r.jsxs)(Vt,{onClick:Se,className:"min-h-[44px] justify-center bg-zinc-950 text-white hover:bg-zinc-800",children:[L.primaryAction.label,(0,r.jsx)(he,{name:"ArrowRight",size:16})]}),(0,r.jsxs)("p",{className:"text-sm text-zinc-500",children:["Scope: ",(0,r.jsx)("span",{className:"font-semibold text-zinc-800",children:L.scope.label})]})]})]}):null,d?(0,r.jsxs)(r.Fragment,{children:[ue?(0,r.jsxs)("div",{className:"rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900","data-testid":"pricing-error-state",children:["Pricing data could not load for ",L.scope.label,". Refresh this page or open setup if the issue continues."]}):null,N?(0,r.jsx)("div",{className:"flex min-h-[260px] items-center justify-center rounded-2xl border border-zinc-200 bg-white","data-testid":"pricing-loading-state",children:(0,r.jsx)(br,{size:"md"})}):(0,r.jsxs)("div",{className:"space-y-5",children:[(0,r.jsx)(Wi,{model:L,onPrimary:Se}),(0,r.jsx)("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3","data-testid":"pricing-landing-tiles",children:L.tiles.map(A=>(0,r.jsx)(Ei,{tile:A,active:c===A.id,onClick:()=>ze(A)},A.id))}),(0,r.jsx)(qi,{opportunities:L.topOpportunities}),G?(0,r.jsx)(Vi,{detail:G,selectedItem:ce,recipe:K,storeOptions:je,selectedStore:C,canManagePrices:Ne,onSavePrice:de,onSelectItem:A=>v(A.rowId),onBack:()=>{m(""),h(""),I("all"),v("")},onSearchChange:h,onCategoryChange:I,onSelectStore:Ae}):null]},`${C||"all"}:${L.state}`)]}):null,(0,r.jsx)(Gi,{enabled:g,tenantId:x,tenant:s,foodCostSources:R,foodCostError:k}),d?(0,r.jsxs)("footer",{"data-testid":"pricing-legal-footer",className:"rounded-2xl border border-zinc-200 bg-white px-4 py-3 text-xs leading-5 text-zinc-600 shadow-sm",children:[L.legalFooter," Competitor context is informational only."]}):null]})})}export{nn as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.