PageSourceSearch

https://www.zr3i.com/assets/FarmDetail-DW2-9yxa.js

js zr3i.com collected 2026-09-25 19:37:00 UTC 128,856 bytes, 1 lines download raw bytes

1import{r as y,j as t,i as _e,c as we}from"./vendor-react-DnPnnzcV.js";import{s as k,l as w,u as L,r as K,p as n,b as Q,A as ae}from"./index-BWFVt2sG.js";import{PolygonDrawer as Ne}from"./PolygonDrawer-4SmVgv_r.js";import{S as ke}from"./SatelliteCheck-HmiUR4iG.js";import"./vendor-query-CvVCWwM3.js";import"./vendor-supabase-2Rdar6Gf.js";import"./leaflet-COpCJxpy.js";import"./search-BfAJ_PUV.js";import"./check-Wi2vjQF2.js";import"./arrow-left-DDTEXIo0.js";import"./loader-circle-D9bK8qqy.js";import"./map-pin-BdxMMLwW.js";import"./trash-2-CCWNb3Nz.js";import"./minus-Df8dF2h6.js";import"./triangle-alert-BwCHVprn.js";import"./undo-2-ir2PFPGR.js";import"./circle-help-DueSap5R.js";import"./hooks-D2iWMQfU.js";import"./leaf-CbrbkTuy.js";import"./droplets-KJ0rqpKr.js";import"./refresh-cw-YX1LuReY.js";const ue=44/12,Se={SA:{climate:.95,notes:"Saudi Arabia - extreme heat stress"},EG:{climate:1,notes:"Egypt - optimal date palm conditions"},AE:{climate:.9,notes:"UAE - extreme heat, humidity"},IQ:{climate:.95,notes:"Iraq - historical orchards"},OM:{climate:.92,notes:"Oman - coastal areas"},TN:{climate:1.02,notes:"Tunisia - olive belt, Mediterranean optimum"},MA:{climate:1,notes:"Morocco - olive belt, Atlas + coastal"},DZ:{climate:.98,notes:"Algeria - olive belt with semi-arid south"},JO:{climate:.95,notes:"Jordan - olive groves, dryland"},PS:{climate:.97,notes:"Palestine - traditional olive cultivation"},LB:{climate:1,notes:"Lebanon - Mediterranean optimum for olives"},SY:{climate:.98,notes:"Syria - olive heartland (Idlib, Aleppo)"},TR:{climate:.97,notes:"Turkey - Aegean olive belt"},ES:{climate:1.05,notes:"Spain - world-leading olive productivity"},default:{climate:1,notes:"Default - no adjustment"}},Ce={"date-palm":{"1-5":{min:8,max:15,uncertainty:40},"6-15":{min:12,max:30,uncertainty:30},"16-30":{min:18,max:42,uncertainty:25},">30":{min:8,max:20,uncertainty:30}},olive:{"1-5":{min:4,max:10,uncertainty:45},"6-15":{min:10,max:25,uncertainty:30},"16-30":{min:20,max:55,uncertainty:25},">30":{min:15,max:40,uncertainty:28}}},Ae=(e,r=8,a="date-palm",s="default")=>{const i=a==="olive"?"olive":"date-palm",l=Ce[i];let o;e<=5?o="1-5":e<=15?o="6-15":e<=30?o="16-30":o=">30";const c=l[o],p=Se[s]?.climate||1,u=(c.min+c.max)/2*p;return{annualKgC:u/ue,annualKgCO2e:u,method:i==="olive"?"Olive: age-based increment — Nardino (2013), Ferrara (2019), Proietti (2014), IPCC AFOLU Ch.5":"Date palm: age-based increment — IPCC (2019) AFOLU Ch.5, Issa et al. (2020)",ageClass:o,uncertainty:c.uncertainty}},qe={date_palm:1,olive:1.15,citrus:.85,mango:1.25,almond:.9,mixed_agroforestry:1.1},Fe=(e=130,r=15,a=15,s={},i="default",l="date_palm")=>{const o=l==="olive",p=Ae(r,8,o?"olive":"date-palm",i),g=p.annualKgCO2e*e/1e3,x=l==="date_palm"||o?1:qe[l]??1,h=g*x,j={conventional:.2,mulching:.45,composting:.6,intercropping:.75};let d=j.conventional;s.mulching&&(d=Math.max(d,j.mulching)),s.composting&&(d=Math.max(d,j.composting)),s.coverCrops&&s.coverCrops>0&&(d=Math.max(d,j.intercropping));const f=d*ue,_=h+f,S=p.uncertainty,q=Math.sqrt(Math.pow(S,2)+Math.pow(25,2));return{treesPerHa:e,biomassSeqTonsHa:h,socSeqTonsHa:f,totalSeqTonsHa:_,uncertainty:q,breakdown:[{category:"Tree Biomass",value:h},{category:"Soil Carbon",value:f}]}},I={fuel:2.68,electricity:.43,machinery:.5,fertilizer:6.3,irrigation:{drip:.1,sprinkler:.15,furrow:.2,basin:.18,bubbler:.12,manual:.05,flood:.25,rainfed:0},livestock:{cattle:1500,sheep:120,goats:100,camels:800},cropResidueBurning:1500,propane:1.51,naturalGas:2,water:.344}
1,Ie=(e,r,a,s,i,l=0,o=0,c=0,p=0,u=0,g=0,x=0,h=0,j=0)=>{const d=r*I.fuel,f=l*I.electricity,_=a*I.machinery,S=s*I.fertilizer,v=e*(I.irrigation[i]||0)*1e3,q=o*I.livestock.cattle,F=c*I.livestock.sheep,E=p*I.livestock.goats,T=u*I.livestock.camels,$=q+F+E+T,D=g*I.cropResidueBurning,O=x*I.propane,C=h*I.naturalGas,A=j*I.water,W=(d+f+_+S+v+$+D+O+C+A)/1e3;return{total:parseFloat(W.toFixed(2)),breakdown:[{name:"Diesel Fuel",value:parseFloat((d/1e3).toFixed(2)),category:"Energy"},{name:"Electricity",value:parseFloat((f/1e3).toFixed(2)),category:"Energy"},{name:"Machinery",value:parseFloat((_/1e3).toFixed(2)),category:"Energy"},{name:"Fertilizer (N)",value:parseFloat((S/1e3).toFixed(2)),category:"Inputs"},{name:"Irrigation",value:parseFloat((v/1e3).toFixed(2)),category:"Water"},{name:"Livestock",value:parseFloat(($/1e3).toFixed(2)),category:"Animals"},{name:"Residue Burning",value:parseFloat((D/1e3).toFixed(2)),category:"Waste"},{name:"Propane/LPG",value:parseFloat((O/1e3).toFixed(2)),category:"Energy"},{name:"Natural Gas",value:parseFloat((C/1e3).toFixed(2)),category:"Energy"},{name:"Water Usage",value:parseFloat((A/1e3).toFixed(2)),category:"Water"}].filter(m=>m.value>0)}},Te=(e,r)=>{const a=r-e;return a>0?{balance:parseFloat(a.toFixed(2)),status:"positive",message:`Net carbon sink: ${a.toFixed(2)} tons CO₂ sequestered annually`}:a<0?{balance:parseFloat(a.toFixed(2)),status:"negative",message:`Net carbon source: ${Math.abs(a).toFixed(2)} tons CO₂ emitted annually`}:{balance:0,status:"neutral",message:"Carbon neutral: emissions balanced by sequestration"}};function Ee(e){return{cars:parseFloat((e/4.6).toFixed(1)),households:parseFloat((e/7.5).toFixed(1)),flights:parseFloat((e/.9).toFixed(1))}}const Re={marketPrice:15};function Pe(e,r,a,s=Re.marketPrice){const i=e*s,l=r/100*i,o={low:Math.max(0,i-l),central:i,high:i+l,currency:"USD"};return{perYear:o,cumulative:{low:o.low*a,central:o.central*a,high:o.high*a,currency:"USD"}}}const z=[{key:"conservative",priceUSD:8,label:{en:"Conservative",ar:"متحفظ",es:"Conservador",fr:"Prudent",ur:"متحفظ"}},{key:"base",priceUSD:15,label:{en:"Base",ar:"أساسي",es:"Base",fr:"Base",ur:"أساسي"}},{key:"optimistic",priceUSD:22,label:{en:"Optimistic",ar:"متفائل",es:"Optimista",fr:"Optimiste",ur:"متفائل"}}],ie={carbonFraction:.47,rootShootRatio:.37},Le={phase1:{jordan:{buffer:16}}},$e={countryScores:{EG:{total:15,buffer:15,category:"Low-Medium"},JO:{total:11,buffer:15,category:"Low-Medium"},PK:{total:26,buffer:16,category:"Medium"}}},B={asymptote:90,k:.085,p:1.6,rootShoot:ie.rootShootRatio,carbonFraction:ie.carbonFraction},me=(e,r=B)=>{if(e<=0)return 0;const{asymptote:a,k:s,p:i}=r;return a*Math.pow(1-Math.exp(-s*e),i)},pe=(e,r=B)=>me(e,r)*(1+r.rootShoot),Me=(e,r=B)=>pe(e,r)*r.carbonFraction,ne=(e,r=B)=>Me(e,r)*(44/12),De=(e,r=B)=>Math.max(0,ne(e+1,r)-ne(e,r)),Oe=e=>{if(!e)return Le.phase1.jordan.buffer;const r=e.toUpperCase();return $e.countryScores[r]?.buffer??16},He=e=>{const r=e.params??B,a=e.plantingYearOffset,s=Oe(e.countryIso2),i=s/100,l=[];let o=0;for(let u=0;u<e.creditingPeriodYears;u++){const g=Math.max(0,u-a),x=me(g,r),h=pe(g,r),j=h*r.carbonFraction,d=j*(44/12),f=De(g,r),_=f*(1-i);o+=_*e.areaHa,l.push({year:u+1,ageYears:g,agbTDmHa:R(x),totalBiomassTDmHa:R(h),carbonTcHa:R(j),co2eStockTco2eHa:R(d),annualIncrementTco2eHa:R(f),cumulativeNetCreditsTco2eHa:R(o/Math.max(e.areaHa,1))})}const c=l.reduce((u,g)=>u+g.co2eStockTco2eHa,0)/Math.max(l.length,1),p=l.reduce((u,g)=>u+g.annualIncrementTco2eHa*e.areaHa,0);return{perYear:l,longTermAverageTco2eHa:R(c),longTermAverageTco2e:R(c*e.areaHa),bufferPct:s,grossLifetimeCreditsTco2e:R(p),netLifetimeCreditsTco2e:R(p*(1-i)),disclaimer:"Indicative — Chapman-Richards growth model with conservative default parameters. Final parameters subject to CPA-level destructive sampling (≥30 trees, ≥3 strata, R²≥0.90) and VVB validation per VM0047 v1.1 §4.2."}},R=e=>Math.round(e*100)/100,Y=[{id:"vm0042",name:"VM0042 - Methodology for Improved Agricultural Land Management",version:"2.2",standard:"verra_vcs",standardDisplay:"Verra VCS",applicableCropTypes:["date_palm","olive","citrus","agroforestry","tree_crops","perennial_crops"],applicableProjectTypes:["agroforestry","improved_management","sustainable_agriculture"],minAreaHectares:1,requiresBaseline:!0,requirements:[{id:"land_eligibility",description:"Land must have been in agricultural use for at least 10 years",mandatory:!0,checkFunction:e=>e.previousLandUse!=="forest"&&e.previousLandUse!=="wetland"},{id:"legal_ownership",description:"Project proponent must have legal r
1ight to claim carbon rights",mandatory:!0,checkFunction:e=>e.hasLegalOwnership},{id:"baseline_data",description:"Baseline scenario must be established",mandatory:!0,checkFunction:e=>e.hasBaseline},{id:"stakeholder_consent",description:"Local stakeholder consultation and consent required",mandatory:!0,checkFunction:e=>e.hasStakeholderConsent},{id:"crop_applicability",description:"Crop type must be eligible under methodology",mandatory:!0,checkFunction:e=>["date_palm","olive","citrus","agroforestry","tree_crops","perennial_crops"].includes(e.cropType)}],pddSections:["Project Description","Applicability Conditions","Project Boundary","Baseline Scenario","Additionality","Quantification of GHG Emission Reductions","Monitoring","Safeguards"],monitoringFrequency:"annual",creditingPeriod:{min:20,max:100,renewable:!0},documentationUrl:"https://verra.org/methodology/vm0042-methodology-for-improved-agricultural-land-management/"},{id:"ar-acm0003",name:"AR-ACM0003 - Afforestation and Reforestation",version:"2.0",standard:"verra_vcs",standardDisplay:"Verra VCS",applicableCropTypes:["forest","plantation","agroforestry"],applicableProjectTypes:["afforestation","reforestation"],minAreaHectares:5,requiresBaseline:!0,requirements:[{id:"land_eligibility",description:"Land must not have been forest for at least 10 years prior",mandatory:!0,checkFunction:e=>e.previousLandUse!=="forest"},{id:"legal_ownership",description:"Legal right to implement project and claim credits",mandatory:!0,checkFunction:e=>e.hasLegalOwnership},{id:"baseline_data",description:"Historical land use documentation required",mandatory:!0,checkFunction:e=>e.hasBaseline},{id:"min_area",description:"Minimum project area of 5 hectares",mandatory:!0,checkFunction:e=>e.areaHectares>=5}],pddSections:["Project Description","Eligibility Criteria","Baseline Scenario Selection","Additionality Demonstration","Carbon Pool Selection","Ex-ante Estimation","Monitoring Plan","Environmental Impact Assessment"],monitoringFrequency:"biennial",creditingPeriod:{min:20,max:60,renewable:!0}},{id:"sdg-agri-001",name:"SDG-Focused Soil Carbon Sequestration in Agriculture",version:"1.1",standard:"sdg_focused",standardDisplay:"SDG-Focused",applicableCropTypes:["date_palm","olive","citrus","agroforestry","crops","smallholder"],applicableProjectTypes:["sustainable_agriculture","improved_management","regenerative"],minAreaHectares:.5,requiresBaseline:!0,requirements:[{id:"smallholder_focus",description:"Methodology designed for smallholder and community projects",mandatory:!1,checkFunction:e=>e.isSmallholder||e.groupProject||!0},{id:"sdg_contribution",description:"Must demonstrate contribution to at least 3 SDGs",mandatory:!0,checkFunction:()=>!0},{id:"stakeholder_consultation",description:"Mandatory stakeholder consultation process",mandatory:!0,checkFunction:e=>e.hasStakeholderConsent},{id:"legal_ownership",description:"Clear land tenure and carbon rights",mandatory:!0,checkFunction:e=>e.hasLegalOwnership}],pddSections:["Project Summary","Stakeholder Consultation","Safeguarding Principles","SDG Impact Assessment","Baseline Scenario","Monitoring Plan","Carbon Quantification"],monitoringFrequency:"annual",creditingPeriod:{min:5,max:20,renewable:!0}},{id:"iso14064-2",name:"ISO 14064-2 - Project Level GHG Accounting",version:"2019",standard:"iso14064",standardDisplay:"ISO 14064",applicableCropTypes:["all"],applicableProjectTypes:["all"],minAreaHectares:0,requiresBaseline:!0,requirements:[{id:"baseline_scenario",description:"Baseline scenario clearly defined",mandatory:!0,checkFunction:e=>e.hasBaseline},{id:"quantification_methodology",description:"GHG quantification methodology documented",mandatory:!0,checkFunction:()=>!0},{id:"uncertainty_assessment",description:"Uncertainty analysis required",mandatory:!0,checkFunction:()=>!0}],pddSections:["Project Description","GHG Sources and Sinks","Baseline Scenario","Project Scenario","Quantification","Uncertainty Assessment","Monitoring","Verification Requirements"],monitoringFrequency:"annual",creditingPeriod:{min:1,max:100,renewable:!0}},{id:"vm0047",name:"VM0047 - Afforestation, Reforestation & Revegetation",version:"1.1",standard:"verra_vcs",standardDisplay:"Verra VCS (ICVCM CCP-approved)",applicableCropTypes:["date_palm","olive","citrus","agroforestry","tree_crops","forest","plantation"],applicableProjectTypes:["afforestation","reforestation","revegetation","agroforestry","improved_management"],minAreaHectares:.5,requiresBaseline:!0,requirements:[{id:"land_eligibility_vm47",description:"Land must not qualify as forest at project start date",mandatory:!0,checkFunction:e=>e.previousLandUse!=="forest"&&e.previousLandUse!=="dense_forest"},{id:"legal_ownership_vm47",description:"Clear land and carbon rights demonstrated",mandatory:!0,checkFunction:e=>e.hasLegalOwnership},{id:"baseline_vm47",description:"Baseline carbon stocks documented for project area",mandatory:!0,checkFunction:e=>e.hasBaseline},{id:"stakeholder_consent_vm47",description:"Free, prior and informed consent from stakeholders",mandatory:!0,checkFunction:e=>e.hasStakeholderConsent},{id:"native_species_vm47",description:"Preference for native species or proven beneficial species",mandatory:!1,checkFunction:()=>!0},{id:"permanence_vm47",description:"Long-term management plan in place",mandatory:!0,checkFunction:()=>!0}],pddSections:["Project Description","Applicability Conditions","Project Boundary","Baseline Scenario & Additionality","Carbon Pool Selection","Quantification of Net GHG Removals","Leakage Assessment","Monitoring Plan","Environmental & Socioeconomic Impacts"],monitoringFrequency:"annual",creditingPeriod:{min:20,max:100,renewable:!0},documentationUrl:"https://verra.org/methodology/vm0047-afforestation-reforestation-and-revegetation/"}];Y.push({id:"plan-vivo",name:"Plan Vivo Standard - Community Land Use Projects",version:"2023",standard:"sdg_focused",standardDisplay:"Plan Vivo",applicableCropTypes:["date_palm","olive","citrus","agroforestry","tree_crops","forest","smallholder","community"],applicableProjectTypes:["agroforestry","reforestation","afforestation","sustainable_agriculture","improved_management","community_forestry"],minAreaHectares:.1,requiresBaseline:!0,requirements:[{id:"community_participation",description:"Strong community participation and governance required",mandatory:!0,checkFunction:e=>e.hasStakeholderConsent&&(e.groupProject||e.isSmallholder||!0)},{id:"fpic",description:"Free, Prior and Informed Consent (FPIC) documented",mandatory:!0,checkFunction:e=>e.hasStakeholderConsent},{id:"land_tenure",description:"Clear land tenure or usage rights demonstrated",mandatory:!0,checkFunction:e=>e.hasLegalOwnership},{id:"livelihood_benefits",description:"Project must demonstrate livelihood co-benefits",mandatory:!0,checkFunction:()=>!0},{id:"biodiversity",description:"Biodiversity assessment and conservation approach required",mandatory:!1,checkFunction:()=>!0}],pddSections:["Project Summary","Land Tenure & Community Rights","Community Participation","Ecosystem Services","Livelihood Impacts","Technical Specifications","Baseline & Additionality","Monitoring & Reporting","Risk Management & Permanence"],monitoringFrequency:"annual",creditingPeriod:{min:10,max:40,renewable:!0},documentationUrl:"https://www.planvivo.org/plan-vivo-standard"});function Be(e){const r=[];return e.cropType==="date_palm"&&e.country==="SA"&&r.push({type:"additionality",severity:"medium",description:"Date palm cultivation is common practice in this region",mitigation:"Document financial barriers or regulatory additionality"}),(e.managementPractices?.includes("organic")||e.managementPractices?.includes("sustainable"))&&r.push({type:"regulatory",severity:"low",description:"Check if sustainable practices are mandated by local regulations",mitigation:"Provide evidence that practices exceed regulatory requirements"}),e.hasBaseline||r.push({type:"data_quality",severity:"high",description:"Missing baseline data will affect credit calculation accuracy",mitigation:"Establish baseline using historical records or conservative defaults"}),r}function Ue(e){const r=[];return(e.previousLandUse==="cropland"||e.previousLandUse==="grazing")&&r.push({type:"leakage",severity:"medium",description:"Risk of activity shifting - previous land use may relocate",mitigation:"Include leakage monitoring and deduction in calculations"}),e.areaHectares>1e3&&r.push({type:"leakage",severity:"low",description:"Large project may influence local market dynamics",mitigation:"Document market conditions and apply appropriate leakage deduction"}),r}function Ve(e){const r=[];return["arid","semi_arid"].includes(e.country)&&r.push({type:"permanence",severity:"medium",description:"Arid climate increases risk of drought-related carbon loss",mitigation:"Include climate adaptation measures and buffer pool contribution"}),["date_palm","olive"].includes(e.cropType)&&r.push({type:"permanence",severity:"low",description:"Some fire risk exists for tree crops",mitigation:"Document fire prevention measures and include in risk assessment"}),e.hasLegalOwnership||r.push({type:"permanence",severity:"high",description:"Unclear land tenure threatens long-term carbon storage",mitigation:"Establish clear land tenure before project registration"}),r}function Ye(e,r){const a=[],s=[],i=[];for(const d of e.requirements){const f=d.checkFunction(r);a.push({criterion:d.description,passed:f,notes:f?void 0:`Required for ${e.standardDisplay} compliance`}),!f&&d.mandatory&&s.push(d.description)}
1e.applicableCropTypes.includes("all")||e.applicableCropTypes.includes(r.cropType)||(a.push({criterion:`Crop type ${r.cropType} is eligible`,passed:!1,notes:`Eligible crops: ${e.applicableCropTypes.join(", ")}`}),s.push(`Crop type '${r.cropType}' not covered by this methodology`)),e.applicableProjectTypes.includes("all")||e.applicableProjectTypes.includes(r.projectType)||(a.push({criterion:`Project type ${r.projectType} is eligible`,passed:!1}),s.push(`Project type '${r.projectType}' not applicable`)),e.minAreaHectares&&r.areaHectares<e.minAreaHectares&&(a.push({criterion:`Minimum area of ${e.minAreaHectares} hectares`,passed:!1}),i.push("Consider grouping with nearby projects to meet minimum area requirement"));const c=[...Be(r),...Ue(r),...Ve(r)],p=a.filter(d=>d.passed).length,u=a.length,g=Math.round(p/u*100);let x;s.length>0?x="not_eligible":g>=90&&c.filter(d=>d.severity==="high").length===0?x="eligible":x="conditional",x==="conditional"&&(r.hasBaseline||i.push("Establish baseline scenario with historical land use data"),c.some(d=>d.type==="additionality")&&i.push("Strengthen additionality demonstration with financial analysis"),r.hasStakeholderConsent||i.push("Conduct stakeholder consultation process"));const h=ze(e,x,s,c),j=`${e.name} requires: baseline establishment, ${e.monitoringFrequency} monitoring, ${e.creditingPeriod.min}-${e.creditingPeriod.max} year crediting period${e.creditingPeriod.renewable?" (renewable)":""}.`;return{methodologyId:e.id,methodologyName:e.name,standard:e.standardDisplay,eligibilityStatus:x,eligibilityScore:g,criteriaResults:a,riskFlags:c,blockingIssues:s,recommendations:i,explanation:h,requirementsSummary:j}}function ze(e,r,a,s){if(r==="eligible")return`Your project appears to be eligible for ${e.name}. This methodology under ${e.standardDisplay} is well-suited for your project type. Continue to the PDD preparation phase to complete your application.`;if(r==="not_eligible")return`Your project cannot currently qualify for ${e.name} because: `+a.map(l=>`• ${l}`).join("; ")+". Consider addressing these issues or exploring alternative methodologies.";const i=s.filter(l=>l.severity==="high");return i.length>0?`Your project may qualify for ${e.name}, but has significant risks that need attention: `+i.map(l=>l.description).join("; ")+". Address these before proceeding with registration.":`Your project is conditionally eligible for ${e.name}. Some requirements need additional documentation or verification. See the recommendations for next steps.`}function Ge(e){return Y.map(r=>Ye(r,e)).sort((r,a)=>{const s={eligible:0,conditional:1,not_eligible:2};return s[r.eligibilityStatus]!==s[a.eligibilityStatus]?s[r.eligibilityStatus]-s[a.eligibilityStatus]:a.eligibilityScore-r.eligibilityScore})}const Ke={verra_vcs:"Verra VCS-aligned",sdg_focused:"SDG-focused",iso14064:"ISO 14064",clean_development_mechanism:"Clean Development Mechanism"},We={afforestation:"Tree planting",reforestation:"Tree planting",agroforestry:"Agroforestry",improved_management:"Improved management"};function ge(e){return{id:e.id,label:e.name,standardLabel:Ke[e.standard]??e.standardDisplay,scope:e.applicableProjectTypes.map(r=>We[r]??r).join(" · "),creditingYears:e.creditingPeriod,monitoringFrequency:e.monitoringFrequency,version:e.version}}Y.map(ge);const se="carbon-m1-1.0.0",oe="carbon-m2-1.0.0",Qe={allometry_date_palm:"issa-2020+ipcc-afolu-2019",allometry_olive:"brahim-2020+nardino-2013+ferrara-2019",soil_carbon:"ipcc-afolu-2019-tier1",footprint:"ipcc-2019-mena-grid-avg",arr_growth:"vm0047-v1.1-chapman-richards",uncertainty:"ipcc-approach-2",revenue_projection:"carbon-credits-market-price"};function Ze(e){const r=He({areaHa:e.areaHa,creditingPeriodYears:e.creditingPeriodYears,countryIso2:e.countryIso2,plantingYearOffset:e.plantingYearOffset,params:B});return{longTermAverageTco2eHa:r.longTermAverageTco2eHa,longTermAverageTco2e:r.longTermAverageTco2e,bufferPct:r.bufferPct,netLifetimeCreditsTco2e:r.netLifetimeCreditsTco2e,grossLifetimeCreditsTco2e:r.grossLifetimeCreditsTco2e,perYear:r.perYear.map(a=>({year:a.year,annualIncrementTco2eHa:a.annualIncrementTco2eHa,cumulativeNetCreditsTco2eHa:a.cumulativeNetCreditsTco2eHa})),disclaimer:r.disclaimer}}function Je(e,r){const a=[];return e.practices.composting||a.push({id:"adopt_composting",title:"Compost on-farm organic residues",rationale:"Composting returns carbon to the soil and reduces synthetic fertilizer demand.",expectedImpact:"sequestration↑",effort:"low"}),e.practices.mulching||a.push({id:"adopt_mulching",title:"Mulch around tree bases",rationale:"Mulch protects soil moisture, lowering irrigation energy and slowing carbon loss.",expectedImpact:"footprint↓",effort:"low"}),(e.practices.coverCropsHa??0)<=0&&a.push({id:"introduce_cover_crops",title:"Introduce a cover crop on bare ground",rationale:"Cover crops add steady soil organic carbon between harvests.",expectedImpact:"sequestration↑",effort:"medium"}),e.footprint?.irrigationType==="flood"&&a.push({id:"switch_to_drip",title:"Move flood plots onto drip irrigation",rationale:"Drip cuts pumping energy and methane from standing water.",expectedImpact:"footprint↓",effort:"high"}),(e.footprint?.fertilizerKg??0)>200*Math.max(e.areaHectares,1)&&a.push({id:"reduce_n_fertilizer",title:"Reduce nitrogen fertilizer rate",rationale:"High N rates emit N₂O directly and inflate your footprint.",expectedImpact:"footprint↓",effort:"medium"}),e.footprint||a.push({id:"log_operations",title:"Log farm operations (fuel, fertilizer, irrigation)",rationale:"Without operations data we can show sequestration but not net balance.",expectedImpact:"confidence↑",effort:"low"}),r.readinessScore<70&&a.push({id:"raise_readiness",title:"Raise carbon readiness by adding evidence",rationale:"Photos, tree counts, and baseline soil samples increase your readiness score.",expectedImpact:"confidence↑",effort:"medium"}),a.slice(0,6)}function ee(e){if(Array.isArray(e))return e.map(ee);if(e&&typeof e=="object"){const r={};for(const a of Object.keys(e).sort()){const s=e[a];s!==void 0&&(r[a]=ee(s))}return r}return e}function Xe(e){const r=JSON.stringify(ee(e));let a=2166136261;for(let s=0;s<r.length;s++)a^=r.charCodeAt(s),a=Math.imul(a,16777619);return"ds-"+(a>>>0).toString(16).padStart(8,"0")}
1function et(e){const r=e.species==="olive"?"olive":e.species==="date-palm"?"date_palm":"other",s=Ge({cropType:r,projectType:"improved_management",areaHectares:e.areaHectares,treeAge:e.treeAgeYears,country:e.country,hasBaseline:!1,hasLegalOwnership:!0,hasStakeholderConsent:!0,isSmallholder:e.areaHectares<10}).find(c=>c.eligibilityStatus!=="not_eligible")??null,i=(s&&Y.find(c=>c.id===s.methodologyId))??Y[0],l=ge(i),o=s?s.eligibilityScore>=75?"high":s.eligibilityScore>=40?"medium":"low":"low";return{summary:l,confidence:o}}function tt(e,r){let a=0;return e.areaHectares>0&&(a+=20),e.treeAgeYears>0&&(e.treeCount??e.treesPerHectare)&&(a+=25),e.footprint&&(a+=20),(e.practices.mulching||e.practices.composting||(e.practices.coverCropsHa??0)>0)&&(a+=15),a+=r==="high"?20:r==="medium"?12:6,Math.min(100,a)}function rt(e,r){return e.footprint?r!=="high"?{id:"upload_baseline_evidence",label:"Upload baseline evidence (tree photos, soil samples)",rationale:"Evidence raises confidence and unlocks a verifier-ready report."}:{id:"invite_verifier",label:"Invite a verifier to review your farm",rationale:"Your assessment is at the highest available confidence — ready for audit."}:{id:"add_footprint_inputs",label:"Add farm operations (fuel, fertilizer, irrigation)",rationale:"Without operations data we can only estimate sequestration, not your net balance."}}function at(e){const r=e.horizonYears??10,a=e.treesPerHectare??(e.treeCount?e.treeCount/Math.max(e.areaHectares,1e-4):130),s=e.species==="olive"?"olive":e.species==="date-palm"?"date_palm":"other",i=Fe(a,e.treeAgeYears,15,{coverCrops:e.practices.coverCropsHa,mulching:e.practices.mulching,composting:e.practices.composting},e.country,s),l=i.totalSeqTonsHa*e.areaHectares,o=l*r;let c=null,p=null;e.footprint&&(c=Ie(e.areaHectares,e.footprint.fuelLiters??0,e.footprint.machineryHours??0,e.footprint.fertilizerKg??0,e.footprint.irrigationType??"drip",e.footprint.electricityKwh??0,e.footprint.livestockCattle??0,e.footprint.livestockSheep??0,e.footprint.livestockGoats??0,e.footprint.livestockCamels??0).total,p=Te(c,l).balance);const u=Ee(l),g=Pe(l,i.uncertainty,r),{summary:x,confidence:h}=et(e),j=tt(e,h),d=z.map(F=>({key:F.key,pricePerTonUsd:F.priceUSD,perYearUsd:l*F.priceUSD,cumulativeUsd:l*F.priceUSD*r})),f=e.areaHectares>0?Ze({areaHa:e.areaHectares,creditingPeriodYears:r,countryIso2:e.country,plantingYearOffset:0}):null,_=Je(e,{readinessScore:j}),S=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`local-${Date.now().toString(16)}`,v=new Date().toISOString(),q=Xe(e);return{version:se,pipelineVersion:oe,formulaVersions:{...Qe},traceability:{assessmentId:S,assessedAt:v,inputDatasetVersion:q,methodologyId:x.id,engineVersion:se,pipelineVersion:oe},methodology:{id:x.id,label:x.label,standardLabel:x.standardLabel,confidence:h},inputs:e,outputs:{annualSequestrationTons:l,cumulativeSequestrationTons:o,annualFootprintTons:c,netBalanceTons:p,equivalents:u,revenue:{perYear:{low:g.perYear.low,central:g.perYear.central,high:g.perYear.high},cumulative:{low:g.cumulative.low,central:g.cumulative.central,high:g.cumulative.high},currency:"USD"},revenueScenarios:d,arr:f,readinessScore:j},recommendations:_,financialAssumptions:[`Pricing scenarios — Conservative $${z[0].priceUSD}/t · Base $${z[1].priceUSD}/t · Optimistic $${z[2].priceUSD}/t`,`Crediting horizon: ${r} years`,`Revenue band uses ±${Math.round(i.uncertainty*10)/10}% uncertainty window on the central estimate`,"All figures USD, before taxes and Zr3i/community shares","Buyer demand and verification outcomes are NOT modelled"],outcomeExplanations:{annualSequestration:"How much CO₂ your farm captures each year, based on tree biomass growth and soil practices.",annualFootprint:"How much CO₂ your farm operations release each year (fuel, fertilizer, irrigation, livestock).",netBalance:"Sequestration minus footprint. A positive number means your farm is a net carbon sink.",revenue:"Estimated annual income if your sequestration converted into credits at today's market price band.",readiness:"How close your farm is to verifier-ready data quality. Higher = fewer gaps for an auditor.",arr:"Long-term planting projection using the Verra VM0047 Chapman-Richards growth model, with the regional buffer pool applied."},assumptions:[`Tree density: ${a.toFixed(0)} trees/ha`,`Country climate factor for ${e.country}`,"Carbon fraction 0.47 (IPCC default)",`Crediting horizon: ${r} years`,"Soil organic carbon baseline: 15 tC/ha"],confidence:{uncertaintyPct:Math.round(i.uncertainty*10)/10,band:h},limitations:["Estimate is not a guarantee of issued credits.","Revenue band reflects market price volatility, not verifier outcomes.",e.footprint?"Footprint uses MENA-average emission factors.":"Footprint not provided — net balance is null."],nextAction:rt(e,h)}}async function it(e,r){let a=null,s=null;try{const{data:i,error:l}=await k.from("carbon_sequestration_calculations").insert({user_id:r,farm_id:e.inputs.farmId,tree_count:e.input
1s.treeCount??null,tree_type:e.inputs.species,tree_age:e.inputs.treeAgeYears,total_sequestration:e.outputs.annualSequestrationTons,methodology:e.methodology.label,uncertainty:e.confidence.uncertaintyPct}).select("id").maybeSingle();l?w.warn("carbon sequestration audit write failed",l):a=i?.id??null}catch(i){w.error("carbon sequestration audit threw",i)}if(e.outputs.annualFootprintTons!=null)try{const{data:i,error:l}=await k.from("carbon_footprint_calculations").insert({user_id:r,farm_id:e.inputs.farmId,total_emissions:e.outputs.annualFootprintTons,fuel_liters:e.inputs.footprint?.fuelLiters??0,electricity_kwh:e.inputs.footprint?.electricityKwh??0,machinery_hours:e.inputs.footprint?.machineryHours??0,fertilizer_amount:e.inputs.footprint?.fertilizerKg??0,irrigation_type:e.inputs.footprint?.irrigationType??"drip"}).select("id").maybeSingle();l?w.warn("carbon footprint audit write failed",l):s=i?.id??null}catch(i){w.error("carbon footprint audit threw",i)}return{sequestrationId:a,footprintId:s}}function nt({farmId:e,country:r="EG"}){const{lang:a}=L(),{userId:s}=K(),[i,l]=y.useState("intro"),[o,c]=y.useState(null),[p,u]=y.useState(!1),[g,x]=y.useState("date-palm"),[h,j]=y.useState(2),[d,f]=y.useState(260),[_,S]=y.useState(15),[v,q]=y.useState(!1),[F,E]=y.useState(!1),[T,$]=y.useState(!1),[D,O]=y.useState(0),[C,A]=y.useState(0),[U,W]=y.useState("drip"),m=y.useMemo(()=>({title:n({en:"Carbon assessment",ar:"تقدير الكربون"},a),intro:n({en:"Estimate how much CO₂ your farm captures, what it emits, and what it could earn — using the validated Zr3i carbon engine.",ar:"قدّر كمية ثاني أكسيد الكربون التي تحتجزها مزرعتك، وما تطلقه، والإيرادات المحتملة — باستخدام محرك الكربون المعتمد في زرعي."},a),start:n({en:"Run carbon assessment",ar:"ابدأ تقدير الكربون"},a),back:n({en:"Back",ar:"رجوع"},a),species:n({en:"Primary species",ar:"النوع الأساسي"},a),speciesDatePalm:n({en:"Date palm",ar:"نخيل التمر"},a),speciesOlive:n({en:"Olive",ar:"زيتون"},a),speciesOther:n({en:"Other",ar:"أخرى"},a),area:n({en:"Area (hectares)",ar:"المساحة (هكتار)"},a),trees:n({en:"Tree count",ar:"عدد الأشجار"},a),age:n({en:"Average tree age (years)",ar:"متوسط عمر الأشجار (سنوات)"},a),practices:n({en:"Practices",ar:"الممارسات"},a),mulching:n({en:"Mulching",ar:"التغطية بالنشارة"},a),composting:n({en:"Composting",ar:"الكمبوست"},a),addFootprint:n({en:"Add farm operations (for net balance)",ar:"أضف عمليات المزرعة (لحساب الميزان الصافي)"},a),fuel:n({en:"Diesel fuel (liters/year)",ar:"وقود الديزل (لتر/سنة)"},a),fertilizerKg:n({en:"Nitrogen fertilizer (kg/year)",ar:"السماد النيتروجيني (كجم/سنة)"},a),irrigation:n({en:"Irrigation type",ar:"نوع الري"},a),compute:n({en:"Compute estimate",ar:"احسب التقدير"},a),estimating:n({en:"Estimating…",ar:"جارٍ التقدير…"},a),summary:n({en:"Summary",ar:"الملخص"},a),sequestration:n({en:"Annual sequestration",ar:"الاحتجاز السنوي"},a),footprintLbl:n({en:"Annual footprint",ar:"البصمة السنوية"},a),net:n({en:"Net balance",ar:"الميزان الصافي"},a),revenue:n({en:"Revenue projection (estimate)",ar:"إسقاط الإيرادات (تقدير)"},a),perYear:n({en:"per year",ar:"سنويًا"},a),overYears:n({en:"over horizon",ar:"خلال الفترة"},a),readiness:n({en:"Carbon readiness",ar:"جاهزية الكربون"},a),methodology:n({en:"Methodology",ar:"المنهجية"},a),confidence:n({en:"Confidence",ar:"الثقة"},a),assumptions:n({en:"Assumptions",ar:"الافتراضات"},a),limitations:n({en:"Limitations",ar:"القيود"},a),nextStep:n({en:"Next step",ar:"الخطوة التالية"},a),runAgain:n({en:"Run another assessment",ar:"تقدير آخر"},a),tons:n({en:"tCO₂e",ar:"طن مكافئ ثاني أكسيد الكربون"},a),estimateBadge:n({en:"Estimate",ar:"تقدير"},a),equivalents:n({en:"That's roughly equivalent to:",ar:"ما يعادل تقريبًا:"},a),eqCars:n({en:"cars off the road for a year",ar:"سيارة بعيدًا عن الطريق لمدة سنة"},a),eqHouseholds:n({en:"household annual energy",ar:"استهلاك أسرة سنوي للطاقة"},a),eqFlights:n({en:"transatlantic flights",ar:"رحلة عابرة للأطلسي"},a),scenarios:n({en:"Revenue scenarios",ar:"سيناريوهات الإيرادات"},a),scenarioConservative:n({en:"Conservative",ar:"متحفظ"},a),scenarioBase:n({en:"Base",ar:"أساسي"},a),scenarioOptimistic:n({en:"Optimistic",ar:"متفائل"},a),arrTitle:n({en:"Long-term planting projection (VM0047)",ar:"إسقاط طويل الأجل للزراعة (VM0047)"},a),arrLTA:n({en:"Long-term average",ar:"المتوسط طويل الأجل"},a),arrNet:n({en:"Net lifetime credits (after buffer)",ar:"الأرصدة الصافية مدى الحياة (بعد المخزن)"},a),arrBuffer:n({en:"Buffer applied",ar:"المخزن المطبق"},a),recommendations:n({en:"Improvement recommendations",ar:"توصيات التحسين"},a),financialAssumptions:n({en:"Financial assumptions",ar:"الافتراضات المالية"},a),whatItMeans:n({en:"What this means",ar:"ماذا يعني ذلك"},a),traceability:n({en:"Scientific traceability",ar:"التتبع العلمي"},a),trEngine:n({en:"Engine version",ar:"إصدار المحرك"},a),trPipeline:n({en:"Pipeline version",ar:"إصدار خط المعالجة"},a),trMethodology:n({en:"Methodology ID",ar:"معرّف المنهجية"},a),trTimestamp:n({en:"Assessment timestamp",ar:"طابع زمني للتقدير"},a),trDataset:n({en:"Input dataset version",ar:"إصدار بيانات الإدخال"},a),trAudit:n({en:"Audit ID",ar:"معرّف التدقيق"},a),effortLow:n({en:"low effort",ar:"جهد منخفض"},a),effortMedium:n({en:"medium effort",ar:"جهد متوسط"},a),effortHigh:n({en:"high effort",ar:"جهد مرتفع"},a)}),[a]);function ve(){return{farmId:e,country:r,areaHectares:h,species:g,treeCount:d,treeAgeYears:_,practices:{mulching:v,composting:F},footprint:T?{fuelLiters:D,fertilizerKg:C,irrigationType:U}:void 0,horizonYears:10}}async function je(){u(!0);try{const b=at(ve());
1c(b),l("results"),s&&it(b,s).catch(H=>w.warn("persistAssessment background failure",H))}catch(b){w.error("runCarbonAssessment threw",b)}finally{u(!1)}}const P=(b,H=1)=>new Intl.NumberFormat(a==="ar"?"ar":"en",{maximumFractionDigits:H}).format(b),V=b=>new Intl.NumberFormat(a==="ar"?"ar":"en",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(b);if(i==="intro")return t.jsxs("section",{className:"rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsx("h2",{className:"text-lg font-semibold",children:m.title}),t.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:m.intro}),t.jsx("button",{type:"button",onClick:()=>l("assess"),className:"mt-4 inline-flex h-11 items-center rounded-xl bg-primary px-5 text-sm font-medium text-primary-foreground hover:opacity-90",children:m.start})]});if(i==="assess")return t.jsxs("section",{className:"space-y-4 rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsx("h2",{className:"text-lg font-semibold",children:m.title}),t.jsxs("div",{className:"space-y-2",children:[t.jsx("label",{className:"block text-sm font-medium",children:m.species}),t.jsx("div",{className:"flex flex-wrap gap-2",children:["date-palm","olive","other"].map(b=>t.jsx("button",{type:"button",onClick:()=>x(b),className:`h-11 rounded-xl border px-4 text-sm font-medium ${g===b?"bg-primary text-primary-foreground":"bg-background hover:bg-muted"}`,children:b==="date-palm"?m.speciesDatePalm:b==="olive"?m.speciesOlive:m.speciesOther},b))})]}),t.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[t.jsxs("label",{className:"block",children:[t.jsx("span",{className:"text-sm font-medium",children:m.area}),t.jsx("input",{type:"number",min:0,step:.1,value:h,onChange:b=>j(parseFloat(b.target.value)||0),className:"mt-1 h-11 w-full rounded-xl border bg-background px-3 text-base"})]}),t.jsxs("label",{className:"block",children:[t.jsx("span",{className:"text-sm font-medium",children:m.trees}),t.jsx("input",{type:"number",min:0,value:d,onChange:b=>f(parseInt(b.target.value)||0),className:"mt-1 h-11 w-full rounded-xl border bg-background px-3 text-base"})]}),t.jsxs("label",{className:"block",children:[t.jsx("span",{className:"text-sm font-medium",children:m.age}),t.jsx("input",{type:"number",min:0,value:_,onChange:b=>S(parseInt(b.target.value)||0),className:"mt-1 h-11 w-full rounded-xl border bg-background px-3 text-base"})]})]}),t.jsxs("fieldset",{className:"space-y-2",children:[t.jsx("legend",{className:"text-sm font-medium",children:m.practices}),t.jsxs("label",{className:"flex items-center gap-3",children:[t.jsx("input",{type:"checkbox",checked:v,onChange:b=>q(b.target.checked),className:"h-5 w-5"}),t.jsx("span",{className:"text-sm",children:m.mulching})]}),t.jsxs("label",{className:"flex items-center gap-3",children:[t.jsx("input",{type:"checkbox",checked:F,onChange:b=>E(b.target.checked),className:"h-5 w-5"}),t.jsx("span",{className:"text-sm",children:m.composting})]})]}),t.jsxs("fieldset",{className:"space-y-2 rounded-xl border bg-background p-3",children:[t.jsxs("label",{className:"flex items-center gap-3",children:[t.jsx("input",{type:"checkbox",checked:T,onChange:b=>$(b.target.checked),className:"h-5 w-5"}),t.jsx("span",{className:"text-sm font-medium",children:m.addFootprint})]}),T&&t.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[t.jsxs("label",{className:"block",children:[t.jsx("span",{className:"text-sm font-medium",children:m.fuel}),t.jsx("input",{type:"number",min:0,value:D,onChange:b=>O(parseFloat(b.target.value)||0),className:"mt-1 h-11 w-full rounded-xl border bg-background px-3 text-base"})]}),t.jsxs("label",{className:"block",children:[t.jsx("span",{className:"text-sm font-medium",children:m.fertilizerKg}),t.jsx("input",{type:"number",min:0,value:C,onChange:b=>A(parseFloat(b.target.value)||0),className:"mt-1 h-11 w-full rounded-xl border bg-background px-3 text-base"})]}),t.jsxs("label",{className:"block",children:[t.jsx("span",{className:"text-sm font-medium",children:m.irrigation}),t.jsxs("select",{value:U,onChange:b=>W(b.target.value),className:"mt-1 h-11 w-full rounded-xl border bg-background px-3 text-base",children:[t.jsx("option",{value:"drip",children:"drip"}),t.jsx("option",{value:"flood",children:"flood"}),t.jsx("option",{value:"sprinkler",children:"sprinkler"})]})]})]})]}),t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("button",{type:"button",onClick:()=>l("intro"),className:"h-11 rounded-xl border px-4 text-sm font-medium hover:bg-muted",children:m.back}),t.jsx("button",{type:"button",onClick:je,disabled:p,className:"h-11 rounded-xl bg-primary px-5 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50",children:p?m.estimating:m.compute})]})]});if(!o)return null;const N=o;return t.jsxs("section",{className:"space-y-4 rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsx("h2",{className:"text-lg font-semibold",children:m.summary}),t.jsx("button",{type:"button",onClick:()=>l("assess"),className:"h-11 rounded-xl border px-4 text-sm font-medium hover:bg-muted",children:m.runAgain})]}),t.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:m.sequestration}),t.jsxs("div",{className:"mt-1 text-2xl font-semibold",children:[P(N.outputs.annualSequestrationTons)," ",m.tons]}),t.jsxs("div",{className:"text-xs text-muted-foreground",children:["±",P(N.confidence.uncertaintyPct),"% · ",m.perYear]})]}),t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:m.footprintLbl}),t.jsx("div",{className:"mt-1 text-2xl font-semibold",children:N.outputs.annualFootprintTons==null?"—":`${P(N.outputs.annualFootprintTons)} ${m.tons}`})]}),t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:m.net}),t.jsx("div",{className:"mt-1 text-2xl font-semibold",children:N.outputs.netBalanceTons==null?"—":`${P(N.outputs.netBalanceTons)} ${m.tons}`})]})]}),t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:m.revenue}),t.jsx("span",{className:"rounded-full bg-amber-100 px-2 py-0.5 text-[10px] font-medium uppercase text-amber-900",children:m.estimateBadge})]}),t.jsxs("div",{className:"mt-1 text-2xl font-semibold",children:[V(N.outputs.revenue.perYear.low)," – ",V(N.outputs.revenue.perYear.high)]}),t.jsxs("div",{className:"text-xs text-muted-foreground",children:[V(N.outputs.revenue.cumulative.low)," – ",V(N.outputs.revenue.cumulative.high)," ",m.overYears]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:N.outcomeExplanations.revenue})]}),t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:m.scenarios}),t.jsx("span",{className:"rounded-full bg-amber-100 px-2 py-0.5 text-[10px] font-medium uppercase text-amber-900",children:m.estimateBadge})]}),t.jsx("div",{className:"mt-2 grid gap-2 sm:grid-cols-3",children:N.outputs.revenueScenarios.map(b=>{const H=b.key==="conservative"?m.scenarioConservative:b.key==="base"?m.scenarioBase:m.scenarioOptimistic;return t.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[t.jsxs("div",{className:"text-xs font-medium",children:[H," · $",b.pricePerTonUsd,"/t"]}),t.jsxs("div",{className:"mt-1 text-base font-semibold",children:[V(b.perYearUsd),t.jsxs("span",{className:"text-xs font-normal text-muted-foreground",children:[" / ",m.perYear]})]}),t.jsxs("div",{className:"text-xs text-muted-foreground",children:[V(b.cumulativeUsd)," ",m.overYears]})]},b.key)})})]}),N.outputs.arr&&t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:m.arrTitle}),t.jsx("span",{className:"rounded-full bg-amber-100 px-2 py-0.5 text-[10px] font-medium uppercase text-amber-900",children:m.estimateBadge})]}),t.jsxs("div",{className:"mt-2 grid gap-3 sm:grid-cols-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-muted-foreground",children:m.arrLTA}),t.jsxs("div",{className:"text-base font-semibold",children:[P(N.outputs.arr.longTermAverageTco2e)," ",m.tons]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-muted-foreground",children:m.arrNet}),t.jsxs("div",{className:"text-base font-semibold",children:[P(N.outputs.arr.netLifetimeCreditsTco2e)," ",m.tons]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-muted-foreground",children:m.arrBuffer}),t.jsxs("div",{className:"text-base font-semibold",children:[N.outputs.arr.bufferPct,"%"]})]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:N.outcomeExplanations.arr})]}),t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:m.equivalents}),t.jsxs("ul",{className:"mt-2 grid gap-1 text-sm sm:grid-cols-3",children:[t.jsxs("li",{children:[P(N.outputs.equivalents.cars)," ",m.eqCars]}),t.jsxs("li",{children:[P(N.outputs.equivalents.households)," ",m.eqHouseholds]}),t.jsxs("li",{children:[P(N.outputs.equivalents.flights)," ",m.eqFlights]})]})]}),t.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:m.methodology}),t.jsx("div",{className:"mt-1 text-sm font-medium",children:N.methodology.label}),t.jsx("div",{className:"text-xs text-muted-foreground",children:N.methodology.standardLabel}),t.jsxs("div",{className:"mt-2 text-xs",children:[m.confidence,": ",t.jsx("span",{className:"font-medium",children:N.methodology.confidence})]})]}),t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:m.readiness}),t.jsxs("div",{className:"mt-1 text-2xl font-semibold",children:[N.outputs.readinessScore,"/100"]}),t.jsx("div",{className:"mt-2 h-2 w-full overflow-hidden rounded-full bg-muted",children:t.jsx("div",{className:"h-full bg-primary",style:{width:`${N.outputs.readinessScore}%`}})}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:N.outcomeExplanations.readiness})]})]}),N.recommendations.length>0&&t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:m.recommendations}),t.jsx("ul",{className:"mt-2 space-y-2",children:N.recommendations.map(b=>{const H=b.effort==="low"?m.effortLow:b.effort==="medium"?m.effortMedium:m.effortHigh;return t.jsxs("li",{className:"rounded-lg border bg-card p-3",children:[t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsx("div",{className:"text-sm font-medium",children:b.title}),t.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[10px] uppercase text-muted-foreground",children:H})]}),t.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:b.rationale}),t.jsx("div",{className:"mt-1 text-[10px] uppercase tracking-wide text-primary",children:b.expectedImpact})]},b.id)})})]}),t.jsxs("details",{className:"rounded-xl border bg-background p-4",children:[t.jsx("summary",{className:"cursor-pointer text-sm font-medium",children:m.assumptions}),t.jsx("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm text-muted-foreground",children:N.assumptions.map(b=>t.jsx("li",{children:b},b))})]}),t.jsxs("details",{className:"rounded-xl border bg-background p-4",children:[t.jsx("summary",{className:"cursor-pointer text-sm font-medium",children:m.financialAssumptions}),t.jsx("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm text-muted-foreground",children:N.financialAssumptions.map(b=>t.jsx("li",{children:b},b))})]}),t.jsxs("details",{className:"rounded-xl border bg-background p-4",children:[t.jsx("summary",{className:"cursor-pointer text-sm font-medium",children:m.limitations}),t.jsx("ul",{className:"mt-2 list-inside list-disc space-y-1 text-sm text-muted-foreground",children:N.limitations.map(b=>t.jsx("li",{children:b},b))})]}),t.jsxs("details",{className:"rounded-xl border bg-background p-4",children:[t.jsx("summary",{className:"cursor-pointer text-sm font-medium",children:m.traceability}),t.jsxs("dl",{className:"mt-2 grid gap-2 text-xs sm:grid-cols-2",children:[t.jsxs("div",{children:[t.jsx("dt",{className:"text-muted-foreground",children:m.trEngine}),t.jsx("dd",{className:"font-mono",children:N.traceability.engineVersion})]}),t.jsxs("div",{children:[t.jsx("dt",{className:"text-muted-foreground",children:m.trPipeline}),t.jsx("dd",{className:"font-mono",children:N.traceability.pipelineVersion})]}),t.jsxs("div",{children:[t.jsx("dt",{className:"text-muted-foreground",children:m.trMethodology}),t.jsx("dd",{className:"font-mono",children:N.traceability.methodologyId})]}),t.jsxs("div",{children:[t.jsx("dt",{className:"text-muted-foreground",children:m.trTimestamp}),t.jsx("dd",{className:"font-mono",children:N.traceability.assessedAt})]}),t.jsxs("div",{children:[t.jsx("dt",{className:"text-muted-foreground",children:m.trDataset}),t.jsx("dd",{className:"font-mono",children:N.traceability.inputDatasetVersion})]}),t.jsxs("div",{children:[t.jsx("dt",{className:"text-muted-foreground",children:m.trAudit}),t.jsx("dd",{className:"font-mono",children:N.traceability.assessmentId})]})]})]}),t.jsxs("div",{className:"rounded-xl border bg-primary/5 p-4",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-primary",children:m.nextStep}),t.jsx("div",{className:"mt-1 text-sm font-medium",children:N.nextAction.label}),t.jsx("div",{className:"text-xs text-muted-foreground",children:N.nextAction.rationale})]})]})}const te=[{claim:"annualFootprintTons",label:{en:"Your farm's annual emissions",ar:"الانبعاثات السنوية لمزرعتك"},required:["footprint.calculation","footprint.activity-records"]}
1,{claim:"annualSequestrationTons",label:{en:"Carbon captured each year",ar:"الكربون المُحتجَز سنويًا"},required:["sequestration.calculation","sequestration.tree-inventory","sequestration.geotagged-photos"]},{claim:"monitoringHistory",label:{en:"Monitoring history",ar:"سجل المراقبة"},required:["monitoring.satellite-trend","monitoring.practice-verification"]}];function st(e){const r=new Map;for(const i of e){const l=r.get(i.matrixRow)??[];l.push(i),r.set(i.matrixRow,l)}const a=te.map(i=>{let l=0,o=0,c=0;for(const u of i.required){const g=r.get(u)??[];if(g.length===0){o++;continue}const x=g.some(d=>d.state==="accepted"||d.state==="automated"),h=g.some(d=>d.state==="rejected"),j=g.some(d=>d.state==="pending"||d.state==="under_review");x&&!h?l++:h&&!x?o++:j?c++:o++}let p;return o>0?p="missing_requirements":c>0?p="awaiting_review":l===i.required.length?p="complete":p="ready",{claim:i.claim,matrixRows:i.required,label:p,satisfied:l,required:i.required.length}}),s=ot(a.map(i=>i.label));return{items:e,claims:a,overall:s}}const Z=["missing_requirements","awaiting_review","ready","complete"];function ot(e){if(e.length===0)return"missing_requirements";let r=Z.length-1;for(const a of e){const s=Z.indexOf(a);s<r&&(r=s)}return Z[r]}async function lt(e){const r=[];try{const{data:a,error:s}=await k.from("farmer_evidence").select("id, file_type, file_name, latitude, longitude, captured_at, verified, description").eq("farm_id",e).order("captured_at",{ascending:!1}).limit(50);if(s)throw s;for(const i of a??[]){const l=i.latitude!=null&&i.longitude!=null,o=i.verified?"accepted":"pending";r.push({id:`fe:${i.id}`,matrixRow:i.file_type?.startsWith("image")?"sequestration.geotagged-photos":"monitoring.field-notes",state:o,provenance:"farmer",summary:i.file_name??i.file_type??"Field evidence",details:i.description??void 0,whyItMatters:i.file_type?.startsWith("image")?"Geotagged photos defend the tree inventory used in the sequestration calculation.":"Field notes contextualize farm operations during the monitoring period.",nextAction:i.verified?void 0:l?"Awaiting coordinator review.":"Re-upload with location enabled so the photo can be tied to your parcel.",capturedAt:i.captured_at,source:"farmer_evidence"})}}catch(a){w.warn("loadFarmEvidence: farmer_evidence read failed",a)}try{const{data:a,error:s}=await k.from("practice_verifications").select("id, practice_type, status, detection_method, confidence_score, verification_date, model_version").eq("farm_id",e).order("verification_date",{ascending:!1}).limit(50);if(s)throw s;for(const i of a??[]){const l=(i.status??"pending").toLowerCase(),o=l==="verified"?"accepted":l==="rejected"?"rejected":l==="in_review"||l==="reviewing"?"under_review":"pending",c=i.confidence_score==null?void 0:i.confidence_score>=.8?"high":i.confidence_score>=.5?"medium":"low";r.push({id:`pv:${i.id}`,matrixRow:"monitoring.practice-verification",state:o,provenance:i.detection_method==="automated"?"automated":"coordinator",summary:i.practice_type??"Practice verification",details:i.detection_method?`Detected by ${i.detection_method}.`:void 0,whyItMatters:"Confirms a project activity claimed in the carbon assessment actually occurred.",nextAction:o==="rejected"?"Submit fresh photos or coordinator countersignature.":o==="accepted"?void 0:"Awaiting reviewer.",confidence:c,capturedAt:i.verification_date,source:"practice_verifications",assessmentVersion:i.model_version??void 0})}}catch(a){w.warn("loadFarmEvidence: practice_verifications read failed",a)}try{const{data:a,error:s}=await k.from("farm_boundaries").select("id").eq("farm_id",e);if(s)throw s;const i=(a??[]).map(l=>l.id);if(i.length>0){const{data:l,error:o}=await k.from("satellite_analyses").select("id, satellite_source, image_date, ndvi_avg, cloud_coverage, analysis_date").in("boundary_id",i).order("image_date",{ascending:!1}).limit(25);if(o)throw o;for(const c of l??[]){const p=c.cloud_coverage!=null&&c.cloud_coverage>.3;r.push({id:`sat:${c.id}`,matrixRow:"monitoring.satellite-trend",state:"automated",provenance:"automated",summary:`Satellite observation (${c.satellite_source})`,details:c.ndvi_avg!=null?`Vegetation index (NDVI) ${Number(c.ndvi_avg).toFixed(2)} on ${c.image_date}.`:void 0,whyItMatters:"Independent vegetation trend that corroborates the on-farm tree inventory.",confidence:p?"low":"automated",capturedAt:c.analysis_date??new Date(c.image_date).toISOString(),source:c.satellite_source??"satellite_analyses"})}}}catch(a){w.warn("loadFarmEvidence: satellite_analyses read failed",a)}try{const{data:a,error:s}=await k.from("palm_trees").select("id, created_at").eq("farm_id",e).limit(1);if(s)throw s;a&&a.length>0&&r.push({id:`inv:${e}`,matrixRow:"sequestration.tree-inventory",state:"accepted",provenance:"farmer",summary:"Tree inventory on record",whyItMatters:"Per-tree inventory anchors the species- and age-class allometry used by VM0042.",capturedAt:a[0].created_at,
1source:"palm_trees"})}catch(a){w.warn("loadFarmEvidence: palm_trees read failed",a)}try{const{data:a,error:s}=await k.from("carbon_sequestration_calculations").select("id, created_at, total_sequestration_tons").eq("farm_id",e).order("created_at",{ascending:!1}).limit(1);if(s)throw s;for(const i of a??[])r.push({id:`calc-seq:${i.id}`,matrixRow:"sequestration.calculation",state:"accepted",provenance:"automated",summary:"Sequestration calculation executed",details:i.total_sequestration_tons!=null?`Result: ${Number(i.total_sequestration_tons).toFixed(2)} tCO₂e.`:void 0,whyItMatters:"The audited calculation produces the headline sequestration figure shown to you.",capturedAt:i.created_at??new Date().toISOString(),source:"carbon_sequestration_calculations",auditId:i.id})}catch(a){w.warn("loadFarmEvidence: carbon_sequestration_calculations read failed",a)}try{const{data:a,error:s}=await k.from("carbon_footprint_calculations").select("id, created_at, total_co2_tons, fuel_liters, fertilizer_amount, irrigation_type").eq("farm_id",e).order("created_at",{ascending:!1}).limit(1);if(s)throw s;for(const i of a??[]){const l=(i.fuel_liters??0)>0||(i.fertilizer_amount??0)>0||!!i.irrigation_type;r.push({id:`calc-fp:${i.id}`,matrixRow:"footprint.calculation",state:"accepted",provenance:"automated",summary:"Footprint calculation executed",details:i.total_co2_tons!=null?`Result: ${Number(i.total_co2_tons).toFixed(2)} tCO₂e.`:void 0,whyItMatters:"Provides the emissions figure subtracted from sequestration in the net balance.",capturedAt:i.created_at??new Date().toISOString(),source:"carbon_footprint_calculations",auditId:i.id}),l&&r.push({id:`calc-fp-act:${i.id}`,matrixRow:"footprint.activity-records",state:"accepted",provenance:"farmer",summary:"Operational activity recorded",whyItMatters:"Fuel, fertilizer, and irrigation entries are the supporting evidence behind the footprint number.",capturedAt:i.created_at??new Date().toISOString(),source:"carbon_footprint_calculations"})}}catch(a){w.warn("loadFarmEvidence: carbon_footprint_calculations read failed",a)}return r}function re(e){const[r,a]=y.useState(null),[s,i]=y.useState(!1),[l,o]=y.useState(0);return y.useEffect(()=>{if(!e)return;let c=!1;return i(!0),lt(e).then(p=>{c||a(st(p))}).finally(()=>{c||i(!1)}),()=>{c=!0}},[e,l]),{bundle:r,loading:s,reload:()=>o(c=>c+1)}}function ct({farmId:e}){const{lang:r}=L(),{bundle:a,loading:s}=re(e),i=y.useMemo(()=>({title:n({en:"Evidence & readiness",ar:"الأدلة والجاهزية"},r),loading:n({en:"Loading evidence…",ar:"جارٍ تحميل الأدلة…"},r),readiness:n({en:"Carbon claim readiness",ar:"جاهزية المطالبات الكربونية"},r),overall:n({en:"Overall",ar:"الإجمالي"},r),bucketAccepted:n({en:"Accepted",ar:"مقبول"},r),bucketPending:n({en:"Pending evidence",ar:"بانتظار الأدلة"},r),bucketReview:n({en:"Under review",ar:"قيد المراجعة"},r),bucketRejected:n({en:"Rejected",ar:"مرفوض"},r),bucketMissing:n({en:"Missing",ar:"ناقص"},r),noItems:n({en:"No items in this bucket.",ar:"لا توجد عناصر في هذه الفئة."},r),whyMatters:n({en:"Why it matters",ar:"أهمية ذلك"},r),nextStep:n({en:"Next step",ar:"الخطوة التالية"},r),source:n({en:"Source",ar:"المصدر"},r),provenance:n({en:"Provenance",ar:"المنشأ"},r),captured:n({en:"Captured",ar:"تاريخ الإلتقاط"},r),details:n({en:"Details",ar:"تفاصيل"},r),matrixRow:n({en:"Evidence matrix row",ar:"صف مصفوفة الأدلة"},r),provFarmer:n({en:"Farmer",ar:"المزارع"},r),provCoordinator:n({en:"Coordinator",ar:"المنسق"},r),provAutomated:n({en:"Automated",ar:"آلي"},r)}),[r]);if(s||!a)return t.jsxs("section",{className:"rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsx("h2",{className:"text-lg font-semibold",children:i.title}),t.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:i.loading})]});const l={accepted:[],automated:[],pending:[],under_review:[],rejected:[],missing:[]};for(const u of a.items)l[u.state].push(u);const o=[...l.accepted,...l.automated],c=new Set(a.items.map(u=>u.matrixRow)),p=te.flatMap(u=>u.required.filter(g=>!c.has(g)).map(g=>({row:g,claim:u.label[r==="ar"?"ar":"en"]})));return t.jsxs("section",{className:"space-y-4 rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsx("h2",{className:"text-lg font-semibold",children:i.title}),t.jsx(le,{label:a.overall,lang:r})]}),t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:i.readiness}),t.jsx("ul",{className:"mt-2 space-y-2",children:a.claims.map(u=>{const g=te.find(h=>h.claim===u.claim),x=g?g.label[r==="ar"?"ar":"en"]:u.claim;return t.jsxs("li",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium",children:x}),t.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.satisfied," / ",u.required," ",n({en:"requirements satisfied",ar:"متطلبًا مستوفى"},r)]})]}),t.jsx(le,{label:u.label,lang:r})]},u.claim)})})]}),t.jsx(G,{title:i.bucketAccepted,tone:"ok",items:o,t:i,lang:r}),t.jsx(G,{title:i.bucketPending,tone:"warn",items:l.pending,t:i,lang:r}),t.jsx(G,{title:i.bucketReview,tone:"info",items:l.under_review,t:i,lang:r}),t.jsx(G,{title:i.bucketRejected,tone:"bad",items:l.rejected,t:i,lang:r}),p.length>0&&t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm font-medium",children:i.bucketMissing}),t.jsx("span",{className:"rounded-full bg-amber-100 px-2 py-0.5 text-[10px] font-medium uppercase text-amber-900",children:p.length})]}),t.jsx("ul",{className:"mt-2 space-y-1",children:p.map((u,g)=>t.jsxs("li",{className:"text-xs text-muted-foreground",children:[t.jsx("span",{className:"font-medium text-foreground",children:u.row}),t.jsx("span",{className:"mx-1",children:"·"}),u.claim]},`${u.row}-${g}`))})]})]})}function G({title:e,tone:r,items:a,t:s,lang:i}){const l=r==="ok"?"bg-emerald-100 text-emerald-900":r==="warn"?"bg-amber-100 text-amber-900":r==="info"?"bg-sky-100 text-sky-900":"bg-rose-100 text-rose-900";return t.jsxs("div",{className:"rounded-xl border bg-background p-4",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm font-medium",children:e}),t.jsx("span",{className:`rounded-full px-2 py-0.5 text-[10px] font-medium uppercase ${l}`,children:a.length})]}),a.length===0?t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:s.noItems}):t.jsx("ul",{className:"mt-2 space-y-2",children:a.map(o=>t.jsx(dt,{item:o,t:s,lang:i},o.id))})]})}function dt({item:e,t:r,lang:a}){const[s,i]=y.useState(!1),l=e.provenance==="farmer"?r.provFarmer:e.provenance==="coordinator"?r.provCoordinator:r.provAutomated;return t.jsxs("li",{className:"rounded-lg border bg-card p-3",children:[t.jsxs("button",{type:"button",onClick:()=>i(o=>!o),className:"flex w-full items-start justify-between gap-3 text-start",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium",children:e.summary}),t.jsxs("div",{className:"text-xs text-muted-foreground",children:[l," · ",new Date(e.capturedAt).toLocaleStr
1ing(a==="ar"?"ar":"en"),e.confidence?` · ${e.confidence}`:""]})]}),t.jsx("span",{className:"text-xs text-muted-foreground",children:s?"−":"+"})]}),s&&t.jsxs("dl",{className:"mt-3 grid gap-2 text-xs sm:grid-cols-2",children:[e.details&&t.jsx(M,{label:r.details,value:e.details}),t.jsx(M,{label:r.whyMatters,value:e.whyItMatters}),e.nextAction&&t.jsx(M,{label:r.nextStep,value:e.nextAction}),t.jsx(M,{label:r.source,value:e.source}),t.jsx(M,{label:r.matrixRow,value:e.matrixRow}),e.methodologyId&&t.jsx(M,{label:"Methodology ID",value:e.methodologyId}),e.assessmentVersion&&t.jsx(M,{label:"Assessment version",value:e.assessmentVersion}),e.auditId&&t.jsx(M,{label:"Audit ID",value:e.auditId})]})]})}function M({label:e,value:r}){return t.jsxs("div",{children:[t.jsx("dt",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:e}),t.jsx("dd",{className:"text-xs text-foreground",children:r})]})}function le({label:e,lang:r}){const s={complete:{en:"Complete",ar:"مكتمل",tone:"bg-emerald-100 text-emerald-900"},ready:{en:"Ready",ar:"جاهز",tone:"bg-sky-100 text-sky-900"},awaiting_review:{en:"Awaiting review",ar:"بانتظار المراجعة",tone:"bg-amber-100 text-amber-900"},missing_requirements:{en:"Missing requirements",ar:"متطلبات ناقصة",tone:"bg-rose-100 text-rose-900"}}[e];return t.jsx("span",{className:`rounded-full px-2 py-0.5 text-[10px] font-medium uppercase ${s.tone}`,children:r==="ar"?s.ar:s.en})}function ut({farmId:e}){const{lang:r}=L(),{bundle:a,loading:s}=re(e),[i,l]=y.useState("all"),o=y.useMemo(()=>({title:n({en:"Monitoring history",ar:"سجل المراقبة"},r),loading:n({en:"Loading timeline…",ar:"جارٍ تحميل السجل…"},r),empty:n({en:"No monitoring events yet.",ar:"لا توجد أحداث مراقبة بعد."},r),all:n({en:"All",ar:"الكل"},r),farmer:n({en:"Farmer",ar:"المزارع"},r),coordinator:n({en:"Coordinator",ar:"المنسق"},r),automated:n({en:"Automated",ar:"آلي"},r)}),[r]);if(s||!a)return t.jsxs("section",{className:"rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsx("h2",{className:"text-lg font-semibold",children:o.title}),t.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:o.loading})]});const c=[...a.items].sort((g,x)=>+new Date(x.capturedAt)-+new Date(g.capturedAt)),p=i==="all"?c:c.filter(g=>g.provenance===i),u=[{id:"all",label:o.all},{id:"farmer",label:o.farmer},{id:"coordinator",label:o.coordinator},{id:"automated",label:o.automated}];return t.jsxs("section",{className:"space-y-3 rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsx("h2",{className:"text-lg font-semibold",children:o.title}),t.jsx("div",{className:"flex flex-wrap gap-2",children:u.map(g=>t.jsx("button",{type:"button",onClick:()=>l(g.id),className:`h-11 rounded-xl border px-4 text-sm font-medium ${i===g.id?"bg-primary text-primary-foreground":"bg-background hover:bg-muted"}`,children:g.label},g.id))}),p.length===0?t.jsx("p",{className:"text-sm text-muted-foreground",children:o.empty}):t.jsx("ol",{className:"relative ms-3 space-y-3 border-s ps-4",children:p.map(g=>t.jsx(mt,{item:g,lang:r},g.id))})]})}function mt({item:e,lang:r}){const a=e.state==="accepted"||e.state==="automated"?"bg-emerald-500":e.state==="rejected"?"bg-rose-500":e.state==="under_review"?"bg-sky-500":"bg-amber-500";return t.jsxs("li",{className:"relative",children:[t.jsx("span",{className:`absolute -start-[1.4rem] top-1.5 h-2.5 w-2.5 rounded-full ${a}`}),t.jsx("div",{className:"text-xs text-muted-foreground",children:new Date(e.capturedAt).toLocaleString(r==="ar"?"ar":"en")}),t.jsx("div",{className:"text-sm font-medium",children:e.summary}),t.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.provenance," · ",e.source," · ",e.state.replace("_"," ")]}),e.details&&t.jsx("div",{className:"mt-1 text-xs text-foreground",children:e.details})]})}const pt=[{id:"vm0042",version:"2.2",label:{en:"VM0042 · Improved Agricultural Land Management",ar:"VM0042 · إدارة محسنة للأراضي الزراعية"},applicableSpecies:["date-palm","olive"],minAreaHectares:1,prohibitedPriorLandUse:["forest","wetland","dense_forest"],mandatoryRules:["min-area","prior-land-use","legal-
1ownership","baseline-established","stakeholder-consent"]},{id:"vm0047",version:"1.1",label:{en:"VM0047 · Afforestation, Reforestation & Revegetation",ar:"VM0047 · التشجير وإعادة التشجير واستعادة الغطاء النباتي"},applicableSpecies:["date-palm","olive"],minAreaHectares:.5,minTreeAgeYears:0,prohibitedPriorLandUse:["forest","dense_forest"],mandatoryRules:["min-area","prior-land-use","legal-ownership","baseline-established","stakeholder-consent","permanence-plan"]}];function fe(e){const r=pt.filter(s=>s.applicableSpecies.includes(e.species));if(r.length===0)return null;const a=r.map(s=>{const i=[],l=[];for(const o of s.mandatoryRules)gt(o,s,e)?i.push(o):l.push(o);return{methodology:s,passed:i,failed:l}});return a.sort((s,i)=>i.passed.length-s.passed.length),a[0]}function gt(e,r,a){switch(e){case"min-area":return a.areaHectares>=r.minAreaHectares;case"prior-land-use":return!a.priorLandUse||!r.prohibitedPriorLandUse.includes(a.priorLandUse);case"legal-ownership":return a.hasLegalOwnership;case"baseline-established":return a.hasBaselineEstablished;case"stakeholder-consent":return a.hasStakeholderConsent;case"permanence-plan":return a.hasPermanencePlan;default:return!1}}const ft={"min-area":{en:"Project area is below the methodology minimum.",ar:"مساحة المشروع أقل من الحد الأدنى للمنهجية.",action:{en:"Add adjacent parcels until the project meets the minimum hectare threshold.",ar:"أضف قطعًا متجاورة حتى يستوفي المشروع الحد الأدنى من الهكتارات."}},"prior-land-use":{en:"Prior land use disqualifies the project under this methodology.",ar:"الاستخدام السابق للأرض يستبعد المشروع وفق هذه المنهجية.",action:{en:"Provide documentation showing the land was not forest or wetland at the start date.",ar:"قدّم وثائق تثبت أن الأرض لم تكن غابة أو أرضًا رطبة في تاريخ بدء المشروع."}},"legal-ownership":{en:"Legal right to claim carbon revenue has not been recorded.",ar:"لم يتم تسجيل الحق القانوني للمطالبة بإيرادات الكربون.",action:{en:"Upload title deed or carbon-rights agreement to the farm record.",ar:"ارفع صك الملكية أو اتفاقية حقوق الكربون إلى سجل المزرعة."}},"baseline-established":{en:"A locked baseline scenario is required before the methodology applies.",ar:"يجب تثبيت سيناريو خط الأساس قبل تطبيق المنهجية.",action:{en:"Open Baseline & lock the current snapshot to create a baseline version.",ar:"افتح خط الأساس وثبّت اللقطة الحالية لإنشاء إصدار خط أساس."}},"stakeholder-consent":{en:"Stakeholder consultation evidence has not been recorded.",ar:"لم يتم تسجيل أدلة استشارة أصحاب المصلحة.",action:{en:"Record at least one stakeholder consultation with attendees and outcomes.",ar:"سجّل جلسة واحدة على الأقل مع أصحاب المصلحة مع الحضور والنتائج."}},"permanence-plan":{en:"Long-term management plan is required for ARR methodologies.",ar:"خطة إدارة طويلة الأمد مطلوبة لمنهجيات التشجير.",action:{en:"Attach a management plan covering the full crediting period.",ar:"أرفق خطة إدارة تغطي فترة الاعتماد بالكامل."}}};function ht(e){if(!e)return"date-palm";const r=e.toLowerCase();return r.includes("olive")?"olive":r.includes("palm")||r.includes("date")?"date-palm":"other"}async function xt(e){const r={farmId:e,species:"date-palm",areaHectares:0,treeAgeYears:0,priorLandUse:null,hasLegalOwnership:!1,hasBaselineEstablished:!1,hasBaselineLocked:!1,baselineVersionNumber:null,hasStakeholderConsent:!1,stakeholderConsultationCount:0,hasPermanencePlan:!1,hasDeforestationFreeDeclaration:!1,latestEligibilityCheck:null,openComplianceTasks:[],hasFarmerConsent:!1};try{const{data:a,error:s}=await k.from("farm_baselines").select("id, total_area_hectares, average_stand_age_years, dominant_variety, prior_land_use, land_ownership_status, deforestation_free_declaration, created_at").eq("farm_id",e).order("created_at",{ascending:!1}).limit(1);if(s)throw s;const i=(a??[])[0];if(i){r.hasBaselineEstablished=!0,r.areaHectares=Number(i.total_area_hectares??0),r.treeAgeYears=Number(i.average_stand_age_years??
10),r.species=ht(i.dominant_variety),r.priorLandUse=i.prior_land_use??null,r.hasLegalOwnership=!!i.land_ownership_status&&["owned","titled","leased_long_term","leased"].includes(i.land_ownership_status.toLowerCase()),r.hasDeforestationFreeDeclaration=!!i.deforestation_free_declaration;const{data:l}=await k.from("baseline_versions").select("version_number").eq("baseline_id",i.id).order("version_number",{ascending:!1}).limit(1),o=(l??[])[0];o&&(r.hasBaselineLocked=!0,r.baselineVersionNumber=Number(o.version_number))}}catch(a){w.warn("loadEligibilityInputs: farm_baselines read failed",a)}try{const{data:a,error:s}=await k.from("mrv_project_farms").select("project_id").eq("farm_id",e);if(s)throw s;const i=Array.from(new Set((a??[]).map(l=>l.project_id)));if(i.length>0){const{data:l,error:o}=await k.from("stakeholder_consultations").select("id, project_id").in("project_id",i).limit(50);if(o)throw o;r.stakeholderConsultationCount=(l??[]).length,r.hasStakeholderConsent=r.stakeholderConsultationCount>0}}catch(a){w.warn("loadEligibilityInputs: stakeholder_consultations read failed",a)}try{const{data:a,error:s}=await k.from("eligibility_checks").select("methodology_id, land_eligibility, additionality_check, regulatory_compliance, environmental_screening, social_screening, overall_eligible, additionality_notes, check_date").order("check_date",{ascending:!1}).limit(1);if(s)throw s;const i=(a??[])[0];i&&(r.latestEligibilityCheck={methodologyId:i.methodology_id??null,landEligibility:i.land_eligibility,additionalityCheck:i.additionality_check,regulatoryCompliance:i.regulatory_compliance,environmentalScreening:i.environmental_screening,socialScreening:i.social_screening,overallEligible:i.overall_eligible,additionalityNotes:i.additionality_notes??null,checkDate:i.check_date??null})}catch(a){w.warn("loadEligibilityInputs: eligibility_checks read failed",a)}try{const{data:a,error:s}=await k.from("compliance_tasks").select("id, title, title_ar, status, priority, due_date, blocker_ref").order("due_date",{ascending:!0}).limit(25);if(s)throw s;r.openComplianceTasks=(a??[]).filter(i=>{const l=(i.status??"").toLowerCase();return l!=="closed"&&l!=="completed"&&l!=="done"}).map(i=>({id:i.id,title:i.title??"Compliance task",titleAr:i.title_ar??null,priority:i.priority??null,dueDate:i.due_date??null,blockerRef:i.blocker_ref??null}))}catch(a){w.warn("loadEligibilityInputs: compliance_tasks read failed",a)}try{const{data:a,error:s}=await k.from("farmer_consents").select("id").eq("farm_id",e).limit(1);if(s)throw s;r.hasFarmerConsent=(a??[]).length>0}catch(a){w.warn("loadEligibilityInputs: farmer_consents read failed",a)}return r.hasPermanencePlan=r.hasDeforestationFreeDeclaration&&r.hasBaselineLocked,r}function bt(e){const r=[yt(e),vt(e),...jt(e),_t(e)],a=fe({species:e.species,areaHectares:e.areaHectares,treeAgeYears:e.treeAgeYears,priorLandUse:e.priorLandUse,hasLegalOwnership:e.hasLegalOwnership,hasBaselineEstablished:e.hasBaselineEstablished,hasStakeholderConsent:e.hasStakeholderConsent,hasPermanencePlan:e.hasPermanencePlan});return{farmId:e.farmId,decisions:r,overall:wt(r.map(s=>s.state)),matchedMethodologyId:a?.methodology.id??null,assessedAt:new Date().toISOString()}}function yt(e){const r={en:"Baseline",ar:"خط الأساس"};return e.hasBaselineEstablished?e.hasBaselineLocked?{domain:"baseline",headline:r,state:"eligible",reason:{en:`Baseline locked at version ${e.baselineVersionNumber??"v1"} with ${e.areaHectares.toFixed(2)} ha and prior land use on record.`,ar:`تم تثبيت خط الأساس عند الإصدار ${e.baselineVersionNumber??"v1"} بمساحة ${e.areaHectares.toFixed(2)} هكتار مع الاستخدام السابق للأرض مسجّل.`},requiredAction:{en:"No action required.",ar:"لا يلزم اتخاذ إجراء."},ruleId:"baseline-locked"}:{domain:"baseline",headline:r,state:"needs_review",reason:{en:"Baseline data is present but no version has been locked, so calculations are not yet defensible.",ar:"بيانات خط الأساس موجودة لكن لم يتم تثبيت إصدار، لذا الحسابات غير قابلة للتثبت بعد."},requiredAction:{en:"Open Baseline & lock the current snapshot to produce a versioned baseline.",ar:"افتح Ø®Ø
1· الأساس وثبّت اللقطة الحالية لإنتاج خط أساس مُصدَّر."},actionHref:"#baseline",ruleId:"baseline-locked"}:{domain:"baseline",headline:r,state:"not_yet_eligible",reason:{en:"No baseline scenario has been recorded for this farm.",ar:"لم يتم تسجيل سيناريو خط الأساس لهذه المزرعة."},requiredAction:{en:"Complete the farm baseline form to record current practice, tree inventory, and prior land use.",ar:"أكمل نموذج خط الأساس لتسجيل الممارسة الحالية وجرد الأشجار والاستخدام السابق للأرض."},actionHref:"#baseline",ruleId:"baseline-established"}}function vt(e){const r={en:"Additionality",ar:"الإضافية"},a=e.latestEligibilityCheck;return!a||a.additionalityCheck==null?{domain:"additionality",headline:r,state:"not_yet_eligible",reason:{en:"Additionality has not been assessed for this farm.",ar:"لم يتم تقييم الإضافية لهذه المزرعة."},requiredAction:{en:"Run the Additionality wizard: select at least two barriers and complete the common-practice test.",ar:"شغّل معالج الإضافية: اختر حاجزين على الأقل وأكمل اختبار الممارسة الشائعة."},actionHref:"#additionality",ruleId:"additionality-recorded"}:a.additionalityCheck===!1?{domain:"additionality",headline:r,state:"not_yet_eligible",reason:{en:a.additionalityNotes?.trim()||"Additionality assessment did not demonstrate barr
1iers + common-practice test.",ar:a.additionalityNotes?.trim()||"لم يثبت تقييم الإضافية الحواجز واختبار الممارسة الشائعة."},requiredAction:{en:"Strengthen the assessment: add a second barrier with documented evidence or revise the common-practice answers.",ar:"عزّز التقييم: أضف حاجزًا ثانيًا بأدلة موثّقة أو راجع إجابات اختبار الممارسة الشائعة."},actionHref:"#additionality",ruleId:"additionality-demonstrated"}:{domain:"additionality",headline:r,state:"eligible",reason:{en:"Additionality demonstrated on the most recent assessment.",ar:"تم إثبات الإضافية في آخر تقييم."},requiredAction:{en:"No action required.",ar:"لا يلزم اتخاذ إجراء."},ruleId:"additionality-demonstrated"}}function jt(e){const r={en:"Methodology fit",ar:"ملاءمة المنهجية"},a=fe({species:e.species,areaHectares:e.areaHectares,treeAgeYears:e.treeAgeYears,priorLandUse:e.priorLandUse,hasLegalOwnership:e.hasLegalOwnership,hasBaselineEstablished:e.hasBaselineEstablished,hasStakeholderConsent:e.hasStakeholderConsent,hasPermanencePlan:e.hasPermanencePlan});return a?a.failed.length===0?[{domain:"methodology",headline:r,state:"eligible",reason:{en:`${a.methodology.id.toUpperCase()} v${a.methodology.version} applies — all ${a.passed.length} mandatory rules pass.`,ar:`${a.methodology.id.toUpperCase()} الإصدار ${a.methodology.version} ينطبق — جميع القواعد الإلزامية (${a.passed.length}) ناجحة.`},requiredAction:{en:"No action required.",ar:"لا يلزم اتخاذ إجراء."},methodologyId:a.methodology.id,ruleId:"methodology-match"}]:a.failed.map(s=>{const i=ft[s];return{domain:"methodology",headline:r,state:"not_yet_eligible",reason:i?{en:i.en,ar:i.ar}:{en:`Rule "${s}" not satisfied for ${a.methodology.id.toUpperCase()}.`,ar:`القاعدة "${s}" غير مستوفاة لـ ${a.methodology.id.toUpperCase()}.`},requiredAction:i?{en:i.action.en,ar:i.action.ar}:{en:"Open the methodology checklist to resolve the failing rule.",ar:"افتح قائمة فحص المنهجية لحل القاعدة الفاشلة."},actionHref:"#methodology",methodologyId:a.methodology.id,ruleId:s}}):[{domain:"methodology",headline:r,state:"not_yet_eligible",reason:{en:"No supported methodology covers this species in v3.6.",ar:"لا توجد منهجية مدعومة تغطي هذا النوع في الإصدار 3.6."},requiredAction:{en:"Confirm the dominant species on the baseline (date palm or olive supported today).",ar:"أكّد النوع السائد في خط الأساس (نخيل التمر أو الزيتون مدعومان حاليًا)."},actionHref:"#baseline",ruleId:"methodology-species"}]}function _t(e){const r={en:"Compliance",ar:"الامتثال"};if(!e.hasFarmerConsent)return{domain:"compliance",headline:r,state:"not_yet_eligible",reason:{en:"Farmer consent record is missing.",ar:"سجل موافقة المزارع مفقود."},requiredAction:{en:"Capture farmer consent in the local language and persist it to the farm record.",ar:"احصل على موافقة المزارع باللغة المحلية واحفظها في سجل المزرعة."},actionHref:"#consent",ruleId:"farmer-consent"};if(e.openComplianceTasks.length>0){const a=e.openComplianceTasks[0];return{domain:"compliance",headline:r,state:"needs_review",reason:{en:`${e.openComplianceTasks.length} open compliance task${e.openComplianceTasks.length===1?"":"s"} — top: "${a.title}".`,ar:`${e.openComplianceTasks.length} مهمة امتثال مفتوحة — الأبرز: «${a.titleAr??a.title}».`},requiredAction:{en:`Resolve task "${a.title}"${a.dueDate?` (due ${a.dueDate})`:""}.`,ar:`أنجز المهمة «${a.titleAr??a.title}»${a.dueDate?` (الموعد ${a.dueDate})`:""}.`},actionHref:"#compliance",ruleId:"compliance-task-open"}}return{domain:"compliance",headline:r,state:"eligible",reason:{en:"Farmer consent on file and no open compliance tasks.",ar:"موافقة المزارع موثقة ولا توجد مهام امتثال مفتوحة."},requiredAction:{en:"No action required.",ar:"لا يلزم اتخاذ إجراء."},ruleId:"compliance-clear"}}const J=["not_yet_eligible","needs_review","eligible"];function wt(e){if(e.length===0)return"not_yet_eligible";let r=J.length-1;for(const a of e){const s=J.indexOf(a);s<r&&(r=s)}return J[r]}function he(e){const[r,a]=y.useState(null),[s,i]=y.useState(!0);return y.useEffect(()=>{if(!e)return;let l=!1;return i(!0),(async()=>{try{const o=await xt(e),c=bt(o);l||a(c)}catch(o){w.warn("useFarmEligibility failed",o),l||a(null)}finally{l||i(!1)}})(),()=>{l=!0}},[e]),{assessment:r,loading:s}}function Nt({farmId:e}){const{lang:r}=L(),{assessment:a,loading:s}=he(e),i=y.useMemo(()=>({title:n({en:"Eligibility & compliance",ar:"الأهلية والامتثال"},r),loading:n({en:"Assessing eligibility…",ar:"جارٍ تقييم الأهلية…"},r),overall:n({en:"Overall decision",ar:"القرار الإجمالي"},r),reason:n({en:"Reason",ar:"السبب"},r),action:n({en:"Required action",ar:"الإجراء المطلوب"},r),methodology:n({en:"Methodology",ar:"المنهجية"},r),domain:{baseline:n({en:"Baseline",ar:"خط الأساس"},r),additionality:n({en:"Additionality",ar:"الإضافية"},r),methodology:n({en:"Methodology fit",ar:"ملاءمة المنهجية"},r),compliance:n({en:"Compliance",ar:"الامتثال"},r)},stateLabel:{eligible:n({en:"Eligible",ar:"مؤهل"},r),not_yet_eligible:n({en:"Not Yet Eligible",ar:"غير مؤهل بعد"},r),needs_review:n({en:"Needs Review",ar:"بحاجة إلى مراجعة"},r)},explainNote:n({en:"Every decision below explains what failed, why it matters, and the next step that changes the status (CR-015).",ar:"كل قرار أدناه يوضّح ما فشل ولماذا يهم وما الخطوة التالية التي تغيّر الحالة (CR-015)."},r)}),[r]);return s||!a?t.jsxs("section",{className:"rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsx("h2",{className:"text-lg font-semibold",children:i.title}),t.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:i.loading})]}):t.jsxs("section",{className:"space-y-4 rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsxs("header",{className:"space-y-1",children:[t.jsx("h2",{className:"text-lg font-semibold",children:i.title}),t.jsx("p",{className:"text-xs text-muted-foreground",children:i.explainNote})]}),t.jsx("div",{className:`rounded-xl border p-4 ${xe(a.overall)}`,"aria-live":"polite",children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:i.overall}),t.jsx("div",{className:"mt-1 text-base font-semibold",children:i.stateLabel[a.overall]})]}),a.matchedMethodologyId&&t.jsxs("div",{className:"text-end text-xs text-muted-foreground",children:[t.jsx("div",{children:i.methodology}),t.jsx("div",{className:"font-mono text-sm text-foreground",children:a.matchedMethodologyId.toUpperCase()})]})]})}),t.jsx("ul",{className:"space-y-3",children:a.decisions.map((l,o)=>t.jsx(kt,{decision:l,t:i},`${l.domain}:${l.ruleId??o}`))})]})}function kt({decision:e,t:r}){const{lang:a}=L();return t.jsxs("li",{className:`rounded-xl border p-4 ${xe(e.state)}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-semibold",children:n(e.headline,a)}),e.methodologyId&&t.jsxs("div",{className:"font-mono text-[11px] text-muted-foreground",children:[e.methodologyId.toUpperCase(),e.ruleId?` · ${e.ruleId}`:""]})]}),t.jsx("span",{className:`shrink-0 rounded-full px-2.5 py-1 text-xs font-medium ${St(e.state)}`,children:r.stateLabel[e.state]})]}),t.jsxs("dl",{className:"mt-3 space-y-2 text-sm",children:[t.jsxs("div",{children:[t.jsx("dt",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:r.reason}),t.jsx("dd",{className:"mt-0.5",children:n(e.reason,a)})]}),t.jsxs("div",{children:[t.jsx("dt",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:r.action}),t.jsx("dd",{className:"mt-0.5",children:e.actionHref?t.jsx("a",{href:e.actionHref,className:"text-primary underline-offset-2 hover:underline",children:n(e.requiredAction,a)}):n(e.requiredAction,a)})]})]})]})}function xe(e){switch(e){case"eligible":return"border-emerald-500/30 bg-emerald-500/5";case"needs_review":return"border-amber-500/30 bg-amber-500/5";case"not_yet_eligible":return"border-border bg-muted/30"}}function St(e){switch(e){case"eligible":return"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300";
1case"needs_review":return"bg-amber-500/15 text-amber-700 dark:text-amber-300";case"not_yet_eligible":return"bg-muted text-muted-foreground"}}const Ct=["draft","submitted","in_review","findings","approved","rejected"];function At(e){return e&&Ct.includes(e)?e:"draft"}function qt(e){return e==="critical"||e==="major"?e:"minor"}function Ft(e){return e==="closed"||e==="responded"?e:"open"}async function It(e){const{data:r,error:a}=await k.from("farms").select("id, user_id").eq("id",e).maybeSingle();if(a||!r?.user_id)return a&&w.warn("verification: farm lookup failed",a),[];const{data:s,error:i}=await k.from("mrv_projects").select("id, name").eq("owner_id",r.user_id);if(i)return w.warn("verification: mrv_projects lookup failed",i),[];const l=(s??[]).map(d=>d.id);if(l.length===0)return[];const o=new Map((s??[]).map(d=>[d.id,d.name])),{data:c,error:p}=await k.from("verification_requests").select("id, project_id, verification_type, vvb_name, submission_date, target_completion_date, actual_completion_date, status, verification_report_url, evidence_package_url, methodology_id, methodologies(name)").in("project_id",l).order("submission_date",{ascending:!1});if(p)return w.warn("verification: requests lookup failed",p),[];const u=c??[];if(u.length===0)return[];const g=u.map(d=>d.id),{data:x,error:h}=await k.from("verification_findings").select("id, verification_id, finding_type, category, severity, description, status, raised_at, resolved_at, response").in("verification_id",g).order("raised_at",{ascending:!1});h&&w.warn("verification: findings lookup failed",h);const j=new Map;for(const d of x??[]){if(!d.verification_id)continue;const f=j.get(d.verification_id)??[];f.push({id:d.id,verificationId:d.verification_id,findingType:d.finding_type,category:d.category??null,severity:qt(d.severity),description:d.description,status:Ft(d.status),raisedAt:d.raised_at??null,resolvedAt:d.resolved_at??null,response:d.response??null}),j.set(d.verification_id,f)}return u.map(d=>{const f=j.get(d.id)??[],_=f.filter(v=>v.status==="open").length,S=f.filter(v=>v.severity==="critical"&&v.status==="open").length;return{id:d.id,projectId:d.project_id??null,projectName:d.project_id?o.get(d.project_id)??null:null,methodologyName:d.methodologies?.name??null,verificationType:d.verification_type,vvbName:d.vvb_name??null,submissionDate:d.submission_date??null,targetCompletionDate:d.target_completion_date??null,actualCompletionDate:d.actual_completion_date??null,status:At(d.status??null),verificationReportUrl:d.verification_report_url??null,evidencePackageUrl:d.evidence_package_url??null,findings:f,openFindings:_,criticalFindings:S}})}const X=["rejected","findings_open","in_progress","not_initiated","verified"];function Tt(e){return e.status==="rejected"?"rejected":e.openFindings>0||e.status==="findings"?"findings_open":e.status==="approved"?"verified":(e.status==="submitted"||e.status==="in_review","in_progress")}function Et(e){if(e.length===0)return"not_initiated";let r=X.length-1;for(const a of e){const s=X.indexOf(a);s<r&&(r=s)}return X[r]}function ce(e,r){switch(e){case"verified":return{label:e,decision:"Verified by an accredited third-party body",reason:r?.vvbName?`${r.vvbName} approved the ${r.verificationType} verification with no open findings.`:"An accredited verification body approved this project with no open findings.",requiredAction:"No action required. Proceed to registry submission and issuance."};case"findings_open":return{label:e,decision:"Verification on hold — corrective actions required",reason:r?`${r.openFindings} open finding(s) raised by ${r.vvbName??"the verification body"}, including ${r.criticalFindings} critical.`:"The verification body has raised findings that must be addressed.",requiredAction:"Respond to each finding with corrective evidence, then ask the coordinator to resubmit."};case"rejected":return{label:e,decision:"Verification rejected",reason:r?`${r.vvbName??"The verification body"} rejected this ${r.verificationType} verification.`:"The verification body rejected the most recent verification request.",requiredAction:"Review the verification report, address the root cause, and open a new verification request."};case"in_progress":return{label:e,decision:"Verification in progress",reason:r?`Submitted ${r.submissionDate??"recently"} to ${r.vvbName??"the verification body"} — currently ${r.status.replace("_"," ")}.`:"A verification request is open with the verification body.",requiredAction:"Keep evidence current; respond promptly if findings are raised."};case"not_initiated":default:return{label:"not_initiated",decision:"Verification not yet initiated",reason:"No verification request has been submitted for this project yet.",requiredAction:"Once eligibility is confirmed and evidence is complete, request a verification through your coordinator."}}}function de(e){if(e.length===0)return{records:[],primary:null,decision:ce("not_initiated",null)};const r=e.map(Tt),a=Et(r),s=e.find((i,l)=>r[l]===a)??e[0]??null;return{records:e,primary:s,decision:ce(a,s)}}function be(e){const[r,a]=y.useState(null),[s,i]=y.useState(!0);return y.useEffect(()=>{if(!e)return;let l=!1;return i(!0),(async()=>{try{const o=await It(e),c=de(o);l||a(c)}catch(o){w.warn("useFarmVerification failed",o),l||a(de([]))}finally{l||i(!1)}})(),()=>{l=!0}},[e]),{status:r,loading:s}}function Rt({farmId:e}){const{lang:r}=L(),{status:a,loading:s}=be(e),i=y.useMemo(()=>({title:n({en:"Verification status",ar:"حالة التحقق"},r),loading:n({en:"Loading verification status…",ar:"جارٍ تحميل حالة التحقق…"},r),overall:n({en:"Decision",ar:"القرار"},r),reason:n({en:"Reason",ar:"السبب"},r),action:n({en:"Required action",ar:"الإجراء المطلوب"},r),history:n({en:"Verification history",ar:"سجل التحقق"},r),none:n({en:"No verification requests have been submitted yet.",ar:"لم يتم تقديم أي طلبات تحقق بعد."},r),explainNote:n({en:"The Verified label only appears when an accredited body has approved this project with no open findings (CR-014).",ar:"تظهر علامة التحقق فقط عندما توافق جهة معتمدة على المشروع دون أي ملاحظات مفتوحة (CR-014)."},r),type:n({en:"Type",ar:"النوع"},r),vvb:n({en:"Verification body",ar:"جهة التحقق"},r),submitted:n({en:"Submitted",ar:"تاريخ التقديم"},r),completed:n({en:"Completed",ar:"تاريخ الإنجاز"},r),findings:n({en:"Findings",ar:"الملاحظات"},r),noFindings:n({en:"No findings raised.",ar:"لا توجد ملاحظات."},r),open:n({en:"open",ar:"مفتوحة"},r),closed:n({en:"closed",ar:"مغلقة"},r),responded:n({en:"responded",ar:"تم الرد"},r),report:n({en:"Verification report",ar:"تقرير التحقق"},r),evidence:n({en:"Evidence package",ar:"حزمة الأدلة"},r),severity:{critical:n({en:"critical",ar:"حرجة"},r),major:n({en:"major",ar:"كبيرة"},r),minor:n({en:"minor",ar:"بسيطة"},r)},labelText:{verified:n({en:"Verified",ar:"تم التحقق"},r),in_progress:n({en:"In Progress",ar:"قيد التنفيذ"},r),findings_open:n({en:"Findings Open",ar:"ملاحظات مفتوحة"},r),rejected:n({en:"Rejected",ar:"مرفوض"},r),not_initiated:n({en:"Not Initiated",ar:"لم يبدأ"},r)}}),[r]);if(s||!a)return t.jsxs("section",{className:"rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsx("h2",{className:"text-lg font-semibold",children:i.title}),t.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:i.loading})]});const l=a.decision;return t.jsxs("section",{className:"space-y-4 rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsxs("header",{className:"space-y-1",children:[t.jsx("h2",{className:"text-lg font-semibold",children:i.title}),t.jsx("p",{className:"text-xs text-muted-foreground",children:i.explainNote})]}),t.jsxs("div",{className:`rounded-xl border p-4 ${Lt(l.label)}`,"aria-live":"polite",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:i.overall}),t.jsx("div",{className:"mt-1 text-base font-semibold",children:l.decision})]}),t.jsx("span",{className:`shrink-0 rounded-full px-2.5 py-1 text-xs font-medium ${$t(l.label)}`,children:i.labelText[l.label]})]}),t.jsxs("dl",{className:"mt-3 space-y-2 text-sm",children:[t.jsxs("div",{children:[t.jsx("dt",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:i.reason}),t.jsx("dd",{className:"mt-0.5",children:l.reason})]}),t.jsxs("div",{children:[t.jsx("dt",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:i.action}),t.jsx("dd",{className:"mt-0.5",children:l.requiredAction})]})]})]}),t.jsxs("div",{children:[t.jsx("h3",{className:"text-sm font-semibold",children:i.history}),a.records.length===0?t.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:i.none}):t.jsx("ul",{className:"mt-3 space-y-3",children:a.records.map(o=>t.jsx(Pt,{record:o,t:i,lang:r},o.id))})]})]})}function Pt({record:e,t:r,lang:a}){const s=i=>i?new Date(i).toLocaleDateString(a==="ar"?"ar":"en"):"—";return t.jsxs("li",{className:"rounded-xl border bg-background p-4",children:[t.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-semibold",children:e.projectName??e.verificationType}),e.methodologyName&&t.jsx("div",{className:"text-[11px] text-muted-foreground",children:e.methodologyName})]}),t.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:e.status.replace("_"," ")})]}),t.jsxs("dl",{className:"mt-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4",children:[t.jsxs("div",{children:[t.jsx("dt",{className:"text-muted-foreground",children:r.type}),t.jsx("dd",{className:"font-medium",children:e.verificationType})]}),t.jsxs("div",{children:[t.jsx("dt",{className:"text-muted-foreground",children:r.vvb}),t.jsx("dd",{className:"font-medium",children:e.vvbName??"—"})]}),t.jsxs("div",{children:[t.jsx("dt",{className:"text-muted-foreground",children:r.submitted}),t.jsx("dd",{className:"font-medium",children:s(e.submissionDate)})]}),t.jsxs("div",{children:[t.jsx("dt",{className:"text-muted-foreground",children:r.completed}),t.jsx("dd",{className:"font-medium",children:s(e.actualCompletionDate)})]})]}),t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:r.findings}),e.findings.length===0?t.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.noFindings}):t.jsx("ul",{className:"mt-2 space-y-2",children:e.findings.map(i=>t.jsxs("li",{className:`rounded-lg border p-3 text-sm ${Mt(i.severity)}`,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:`rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase ${Dt(i.severity)}`,children:r.severity[i.severity]}),i.category&&t.jsx("span",{className:"text-[11px] text-muted-foreground",children:i.category})]}),t.jsx("span",{className:"text-[11px] uppercase text-muted-foreground",children:i.status==="closed"?r.closed:i.status==="responded"?r.responded:r.open})]}),t.jsx("p",{className:"mt-1.5",children:i.description}),i.response&&t.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["↳ ",i.response]})]},i.id))})]}),(e.verificationReportUrl||e.evidencePackageUrl)&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.verificationReportUrl&&t.jsxs("a",{href:e.verificationReportUrl,target:"_blank",rel:"noreferrer noopener",className:"inline-flex h-9 items-center rounded-lg border px-3 text-xs font-medium hover:bg-muted",children:[r.report," ↗"]}),e.evidencePackageUrl&&t.jsxs("a",{href:e.evidencePackageUrl,target:"_blank",rel:"noreferrer noopener",className:"inline-flex h-9 items-center rounded-lg border px-3 text-xs font-medium hover:bg-muted",children:[r.evidence," ↗"]})]})]})}function Lt(e){switch(e){case"verified":return"border-emerald-500/30 bg-emerald-500/5";case"findings_open":return"border-amber-500/30 bg-amber-500/5";case"rejected":return"border-destructive/30 bg-destructive/5";case"in_progress":return"border-sky-500/30 bg-sky-500/5";case"not_initiated":return"border-border bg-muted/30"}}function $t(e){switch(e){case"verified":return"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300";
1case"findings_open":return"bg-amber-500/15 text-amber-700 dark:text-amber-300";case"rejected":return"bg-destructive/15 text-destructive";case"in_progress":return"bg-sky-500/15 text-sky-700 dark:text-sky-300";case"not_initiated":return"bg-muted text-muted-foreground"}}function Mt(e){switch(e){case"critical":return"border-destructive/30 bg-destructive/5";case"major":return"border-amber-500/30 bg-amber-500/5";case"minor":return"border-border bg-background"}}function Dt(e){switch(e){case"critical":return"bg-destructive/15 text-destructive";case"major":return"bg-amber-500/15 text-amber-700 dark:text-amber-300";case"minor":return"bg-muted text-muted-foreground"}}function Ot(e){const r=e.evidence?.overall??"missing_requirements",a=e.eligibility?.overall??"not_yet_eligible",s=e.verification?.decision.label??"not_initiated",i=r==="complete"||r==="ready",l=e.submissions.some(p=>p.status==="issued"||p.status==="approved"),o=e.submissions.some(p=>p.status==="submitted"||p.status==="pending"||p.status==="in_review");let c;if(l){const p=e.submissions.find(u=>u.status==="issued"||u.status==="approved");c={label:"issued",decision:"Credits issued by the registry",reason:p?.registryProjectId?`${p.registryName} issued ${p.creditsApproved??"—"} credits under registry project ${p.registryProjectId}.`:`${p?.registryName??"The registry"} approved your most recent submission.`,requiredAction:"List the issued credits on the marketplace or transfer them to a buyer."}}else if(o){const p=e.submissions.find(u=>u.status==="submitted"||u.status==="pending"||u.status==="in_review");c={label:"submitted",decision:"Registry submission in progress",reason:`${p?.registryName??"Registry"} is processing the ${p?.submissionType??"submission"} (${p?.status??"pending"}).`,requiredAction:"Respond promptly to any registry queries; no further action is required until they reply."}}else a!=="eligible"?c={label:"eligibility_blocked",decision:"Project is not yet eligible for registry submission",reason:"One or more eligibility, baseline, additionality, or compliance checks have not been cleared.",requiredAction:"Open the Eligibility & Compliance section above and resolve every flagged decision."}:i?s==="not_initiated"?c={label:"verification_required",decision:"Ready to request third-party verification",reason:"Eligibility is cleared and evidence is complete. A verification body must now audit the project before a registry submission.",requiredAction:"Request a verification — this opens a new request with your coordinator and the VVB.",primaryAction:{kind:"request-verification",label:"Request verification"}}:s==="in_progress"?c={label:"verification_in_progress",decision:"Verification under way",reason:"A verification request is already open with the verification body.",requiredAction:"Keep evidence current; respond promptly if findings are raised."}:s==="findings_open"?c={label:"verification_in_progress",decision:"Verification on hold — corrective actions required",reason:"The verification body has raised findings that must be closed.",requiredAction:"Open the Verification section and respond to every open finding."}:s==="rejected"?c={label:"not_ready",decision:"Verification was rejected — registry submission blocked",reason:"The most recent verification request was rejected by the verification body.",requiredAction:"Address the root cause in the Verification section and request a new verification."}:s==="verified"?c={label:"ready_for_registry",decision:"Ready to generate a registry-ready package",reason:"Eligibility is cleared, evidence is complete, and the project is verified.",requiredAction:"Generate the registry package to record a submission and start the issuance workflow.",primaryAction:{kind:"generate-package",label:"Generate registry package"}}:c={label:"not_ready",decision:"Project not yet ready for registry submission",reason:"One or more upstream checks are not in a passing state.",requiredAction:"Resolve the items flagged in the Eligibility, Evidence, and Verification sections."}:c={label:"evidence_incomplete",decision:"Evidence pack is incomplete",reason:"The Carbon Evidence Matrix has required rows still missing, pending, or rejected.",requiredAction:"Open the Evidence section and address every missing or rejected row."};return{decision:c,submissions:e.submissions,projectId:e.projectId,context:{hasEvidence:i,evidenceLabel:r,eligibilityLabel:a,verificationLabel:s,annualSequestrationTons:e.annualSequestrationTons}}}async function Ht(e){const{data:r,error:a}=await k.from("farms").select("id, user_id").eq("id",e).maybeSingle();if(a||!r?.user_id)return{projectId:null,submissions:[]};const{data:s,error:i}=await k.from("mrv_projects").select("id").eq("owner_id",r.user_id).order("created_at",{ascending:!0}).limit(1);if(i)return w.warn("registry: project lookup failed",i),{projectId:null,submissions:[]};const l=s?.[0]?.id??null;if(!l)return{projectId:null,submissions:[]};const{data:o,error:c}=await k.from("registry_submissions").select("id, project_id, registry_name, submission_type, status, submission_date, registry_project_id, credits_requested, credits_approved").eq("project_id",l).order("submission_date",{ascending:!1});if(c)return w.warn("registry: submissions lookup failed",c),{projectId:l,submissions:[]};const p=(o??[]).map(u=>({id:u.id,projectId:u.project_id??null,registryName:u.registry_name,submissionType:u.submission_type,status:u.status??"pending",submissionDate:u.submission_date??null,registryProjectId:u.registry_project_id??null,creditsRequested:u.credits_requested??null,creditsApproved:u.credits_approved??null}));return{projectId:l,submissions:p}}function Bt(e,r){const{assessment:a,loading:s}=he(e),{bundle:i,loading:l}=re(e),{status:o,loading:c}=be(e),[p,u]=y.useState(null),[g,x]=y.useState([]),[h,j]=y.useState(!0),[d,f]=y.useState(0);y.useEffect(()=>{if(!e)return;let q=!1;return j(!0),(async()=>{try{const{projectId:F,submissions:E}=await Ht(e);q||(u(F),x(E))}catch(F){w.warn("useRegistryReadiness load failed",F)}finally{q||j(!1)}})(),()=>{q=!0}},[e,d]);const _=y.useCallback(()=>f(q=>q+1),[]),S=s||l||c||h;return{readiness:S?null:Ot({eligibility:a,evidence:i,verification:o,submissions:g,projectId:p,annualSequestrationTons:r}),loading:S,refresh:_,projectId:p}}async function Ut(e){const r=typeof e=="string"?e:JSON.stringify(e),a=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(s)).map(i=>i.toString(16).padStart(2,"0")).join("")}async function ye(e){try{const r=await Ut({...e.payload,_ts:Date.now()}),{error:a}=await k.from("audit_records").insert({record_type:e.recordType,record_id:e.recordId,action:e.action,performed_by:e.performedBy,payload_snapshot:e.payload,record_hash:r,hash_algorithm:"sha256"});a&&w.warn("audit_records insert failed",a)}catch(r){w.warn("audit hashing failed",r)}}async function Vt(e){try{const{data:r,error:a}=await k.from("verification_requests").insert({project_id:e.projectId,verification_type:e.verificationType??"baseline",vvb_name:e.vvbName??null,submission_date:new Date().toISOString().slice(0,10),status:"submitted",created_by:e.userId}).select("id").maybeSingle();if(a)return w.warn("requestVerification failed",a),{id:null,error:a.message};const s=r?.id??null;return s&&await ye({recordType:"verification_request",recordId:s,action:"create",performedBy:e.userId,payload:{project_id:e.projectId,verification_type:e.verificationType??"baseline",vvb_name:e.vvbName??null}}),{id:s,error:null}}catch(r){const a=r instanceof Error?r.message:"unknown error";return w.error("requestVerification threw",r),{id:null,error:a}}}async function Yt(e){try{const{data:r,error:a}=await k.from("registry_submissions").insert({project_id:e.projectId,registry_name:e.registryName??"Verra",submission_type:"issuance",status:"pending",submission_date:new Date().toISOString().slice(0,10),credits_requested:e.estimatedCredits??null,submission_documents:{generated_by:e.userId,generated_at:new Date().toISOString(),evidence_snapshot:e.evidenceMatrixSnapsh
1ot},created_by:e.userId}).select("id").maybeSingle();if(a)return w.warn("generateRegistryPackage failed",a),{id:null,error:a.message};const s=r?.id??null;return s&&await ye({recordType:"registry_submission",recordId:s,action:"create",performedBy:e.userId,payload:{project_id:e.projectId,registry_name:e.registryName??"Verra",credits_requested:e.estimatedCredits??null}}),{id:s,error:null}}catch(r){const a=r instanceof Error?r.message:"unknown error";return w.error("generateRegistryPackage threw",r),{id:null,error:a}}}function zt({farmId:e,annualSequestrationTons:r}){const{lang:a}=L(),{userId:s}=K(),{readiness:i,loading:l,refresh:o,projectId:c}=Bt(e,r),[p,u]=y.useState(!1),[g,x]=y.useState(null),h=y.useMemo(()=>({title:n({en:"Registry & issuance",ar:"السجل والإصدار"},a),loading:n({en:"Computing registry readiness…",ar:"جارٍ حساب جاهزية السجل…"},a),overall:n({en:"Decision",ar:"القرار"},a),reason:n({en:"Reason",ar:"السبب"},a),action:n({en:"Required action",ar:"الإجراء المطلوب"},a),submissions:n({en:"Submission history",ar:"سجل التقديمات"},a),none:n({en:"No registry submissions yet.",ar:"لا توجد تقديمات إلى السجل بعد."},a),noProject:n({en:"This farm has not joined a carbon project yet. Your coordinator needs to add the farm to a project before anything can be sent to the registry.",ar:"لم تنضم هذه المزرعة إلى مشروع كربون بعد. يجب على المنسق إضافة المزرعة إلى مشروع قبل إرسال أي شيء إلى السجل."},a),explain:n({en:"Registry submissions are only generated when eligibility, evidence, and verification all pass (CR-014).",ar:"لا يتم إنشاء التقديمات إلى السجل إلا عند اجتياز الأهلية والأدلة والتحقق جميعًا (CR-014)."},a),requesting:n({en:"Requesting verification…",ar:"جارٍ طلب التحقق…"},a),generating:n({en:"Generating package…",ar:"جارٍ إنشاء الحزمة…"},a),requestOk:n({en:"Verification request submitted.",ar:"تم تقديم طلب التحقق."},a),packageOk:n({en:"Registry package generated.",ar:"تم إنشاء حزمة السجل."},a),failed:n({en:"Action failed. Please try again.",ar:"فشل الإجراء. حاول مجددًا."},a),registry:n({en:"Registry",ar:"السجل"},a),type:n({en:"Type",ar:"النوع"},a),status:n({en:"Status",ar:"الحالة"},a),submitted:n({en:"Submitted",ar:"مقدمة"},a),credits:n({en:"Credits",ar:"الأرصدة"},a),registryProjectId:n({en:"Registry ID",ar:"معرّف السجل"},a),labelText:{not_ready:n({en:"Not Ready",ar:"غير جاهز"},a),evidence_incomplete:n({en:"Evidence Incomplete",ar:"الأدلة غير مكتملة"},a),eligibility_blocked:n({en:"Eligibility Blocked",ar:"الأهلية متوقفة"},a),verification_required:n({en:"Verification Required",ar:"التحقق مطلوب"},a),verification_in_progress:n({en:"Verification In Progress",ar:"التحقق قيد التنفيذ"},a),ready_for_registry:n({en:"Ready for Registry",ar:"جاهز للسجل"},a),submitted:n({en:"Submitted",ar:"تم التقديم"},a),issued:n({en:"Issued",ar:"تم الإصدار"},a)}}),[a]);if(l||!i)return t.jsxs("section",{className:"rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsx("h2",{className:"text-lg font-semibold",children:h.title}),t.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:h.loading})]});const{decision:j}=i;async function d(){if(!c||!s){x(h.noProject);return}u(!0),x(null);try{const{id:_,error:S}=await Vt({projectId:c,userId:s});S||!_?x(h.failed):(x(h.requestOk),o())}catch(_){w.error("requestVerification UI error",_),x(h.failed)}finally{u(!1)}}async function f(){if(!(!c||!s||!i)){u(!0),x(null);try{const{id:_,error:S}=await Yt({projectId:c,userId:s,estimatedCredits:i.context.annualSequestrationTons!=null?Math.max(0,Math.round(i.context.annualSequestrationTons)):void 0,evidenceMatrixSnapshot:{eligibility:i.context.eligibilityLabel,evidence:i.context.evidenceLabel,verification:i.context.verificationLabel}});S||!_?x(h.failed):(x(h.packageOk),o())}catch(_){w.error("generateRegistryPackage UI error",_),x(h.failed)}finally{u(!1)}}}return t.jsxs("section",{className:"space-y-4 rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsxs("header",{className:"space-y-1",children:[t.jsx("h2",{className:"text-lg font-semibold",children:h.title}),t.jsx("p",{className:"text-xs text-muted-foreground",children:h.explain})]}),!c&&t.jsx("p",{className:"rounded-xl border border-amber-500/30 bg-amber-500/5 p-3 text-sm",children:h.noProject}),t.jsxs("div",{className:`rounded-xl border p-4 ${Kt(j.label)}`,"aria-live":"polite",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:h.overall}),t.jsx("div",{className:"mt-1 text-base font-semibold",children:j.decision})]}),t.jsx("span",{className:`shrink-0 rounded-full px-2.5 py-1 text-xs font-medium ${Wt(j.label)}`,children:h.labelText[j.label]})]}),t.jsxs("dl",{className:"mt-3 space-y-2 text-sm",children:[t.jsxs("div",{children:[t.jsx("dt",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:h.reason}),t.jsx("dd",{className:"mt-0.5",children:j.reason})]}),t.jsxs("div",{children:[t.jsx("dt",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:h.action}),t.jsx("dd",{className:"mt-0.5",children:j.requiredAction})]})]}),j.primaryAction&&c&&s&&t.jsx("div",{className:"mt-3",children:t.jsx("button",{type:"button",disabled:p,onClick:j.primaryAction.kind==="request-verification"?d:f,className:"inline-flex h-11 items-center rounded-xl bg-primary px-5 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50",children:p?j.primaryAction.kind==="request-verification"?h.requesting:h.generating:j.primaryAction.label})}),g&&t.jsx("p",{className:"mt-3 text-xs text-muted-foreground",role:"status",children:g})]}),t.jsxs("div",{children:[t.jsx("h3",{className:"text-sm font-semibold",children:h.submissions}),i.submissions.length===0?t.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:h.none}):t.jsx("ul",{className:"mt-3 space-y-2",children:i.submissions.map(_=>t.jsx(Gt,{s:_,t:h,lang:a},_.id))})]})]})}function Gt({s:e,t:r,lang:a}){const s=i=>i?new Date(i).toLocaleDateString(a==="ar"?"ar":"en"):"—";return t.jsxs("li",{className:"rounded-xl border bg-background p-3",children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-semibold",children:e.registryName}),t.jsx("div",{className:"text-[11px] text-muted-foreground",children:e.submissionType})]}),t.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:e.status})]}),t.jsxs("dl",{className:"mt-2 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4",children:[t.jsxs("div",{children:[t.jsx("dt",{className:"text-muted-foreground",children:r.submitted}),t.jsx("dd",{className:"font-medium",children:s(e.submissionDate)})]}),t.jsxs("div",{children:[t.jsx("dt",{className:"text-muted-foreground",children:r.credits}),t.jsx("dd",{className:"font-medium",children:e.creditsApproved!=null?`${e.creditsApproved} / ${e.creditsRequested??"—"}`:e.creditsRequested??"—"})]}),t.jsxs("div",{className:"col-span-2",children:[t.jsx("dt",{className:"text-muted-foreground",children:r.registryProjectId}),t.jsx("dd",{className:"font-mono text-[11px]",children:e.registryProjectId??"—"})]})]})]})}function Kt(e){switch(e){case"issued":case"ready_for_registry":return"border-emerald-500/30 bg-emerald-500/5";case"submitted":case"verification_in_progress":return"border-sky-500/30 bg-sky-500/5";case"verification_required":return"border-primary/30 bg-primary/5";case"evidence_incomplete":case"eligibility_blocked":return"border-amber-500/30 bg-amber-500/5";case"not_ready":return"border-destructive/30 bg-destructive/5"}}function Wt(e){switch(e){case"issued":case"ready_for_registry":return"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300";
1case"submitted":case"verification_in_progress":return"bg-sky-500/15 text-sky-700 dark:text-sky-300";case"verification_required":return"bg-primary/15 text-primary";case"evidence_incomplete":case"eligibility_blocked":return"bg-amber-500/15 text-amber-700 dark:text-amber-300";case"not_ready":return"bg-destructive/15 text-destructive"}}function Qt({farmId:e}){const{lang:r}=L(),{userId:a}=K(),[s,i]=y.useState([]),[l,o]=y.useState(!1),[c,p]=y.useState(null),[u,g]=y.useState(""),x={title:n({en:"Field evidence",ar:"أدلة ميدانية"},r),help:n({en:"Attach geotagged photos of your farm — trees, irrigation, soil, and boundary posts. Each upload strengthens your Verra evidence chain.",ar:"أرفق صورًا لمزرعتك مع تحديد الموقع — الأشجار والري والتربة وحدود الأرض. كل تحميل يعزز سلسلة أدلة Verra."},r),pick:n({en:"Choose photo",ar:"اختر صورة"},r),describe:n({en:"Optional caption",ar:"تعليق اختياري"},r),empty:n({en:"No evidence uploaded yet.",ar:"لم يتم تحميل أي أدلة بعد."},r),uploading:n({en:"Uploading…",ar:"جارٍ الرفع…"},r),verified:n({en:"Verified",ar:"موثّق"},r),pending:n({en:"Pending review",ar:"قيد المراجعة"},r),saved:n({en:"Uploaded.",ar:"تم الرفع."},r),failed:n({en:"Upload failed. Please try again.",ar:"فشل الرفع. حاول مرة أخرى."},r)};async function h(){const{data:f,error:_}=await k.from("farmer_evidence").select("id, file_url, file_name, file_type, description, latitude, longitude, captured_at, verified").eq("farm_id",e).order("captured_at",{ascending:!1}).limit(30);if(_){w.warn("evidence load failed",_);return}i(f??[])}y.useEffect(()=>{e&&h()},[e]);async function j(){return typeof navigator>"u"||!navigator.geolocation?{lat:null,lng:null}:new Promise(f=>{navigator.geolocation.getCurrentPosition(_=>f({lat:_.coords.latitude,lng:_.coords.longitude}),()=>f({lat:null,lng:null}),{timeout:5e3})})}async function d(f){const _=f.target.files?.[0];if(f.target.value="",!(!_||!a)){o(!0),p(null);try{const S=await j(),v=`${a}/${e}/${Date.now()}-${_.name.replace(/[^a-zA-Z0-9._-]/g,"_")}`,q=await k.storage.from("farmer-documents").upload(v,_,{contentType:_.type||"application/octet-stream",upsert:!1});if(q.error)throw q.error;const{data:F}=await k.storage.from("farmer-documents").createSignedUrl(v,60*60*24*365),E=F?.signedUrl??v,T=await k.from("farmer_evidence").insert({farm_id:e,user_id:a,file_url:E,file_name:_.name,file_type:_.type||"image",description:u.trim()||null,latitude:S.lat,longitude:S.lng,captured_at:new Date().toISOString()});if(T.error)throw T.error;g(""),p(x.saved),await h()}catch(S){w.warn("evidence upload failed",S),p(x.failed)}finally{o(!1)}}}return t.jsxs("section",{className:"rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsx("h2",{className:"text-lg font-semibold",children:x.title}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:x.help}),t.jsxs("div",{className:"mt-4 space-y-3",children:[t.jsxs("label",{className:"block",children:[t.jsx("span",{className:"text-sm font-medium",children:x.describe}),t.jsx("input",{type:"text",value:u,onChange:f=>g(f.target.value),className:"mt-1 h-11 w-full rounded-xl border bg-background px-3 text-base"})]}),t.jsxs("label",{className:"inline-flex h-11 cursor-pointer items-center rounded-xl bg-primary px-5 text-sm font-medium text-primary-foreground hover:opacity-90",children:[l?x.uploading:x.pick,t.jsx("input",{type:"file",accept:"image/*,audio/*",capture:"environment",onChange:d,disabled:l,className:"sr-only"})]}),c&&t.jsx("p",{className:"text-xs text-muted-foreground",children:c})]}),s.length===0?t.jsx("p",{className:"mt-4 text-sm text-muted-foreground",children:x.empty}):t.jsx("ul",{className:"mt-4 grid grid-cols-2 gap-3 sm:grid-cols-3",children:s.map(f=>t.jsxs("li",{className:"overflow-hidden rounded-xl border bg-background",children:[f.file_type?.startsWith("image")?t.jsx("img",{src:f.file_url,alt:f.description?`Field evidence photo: ${f.description}`:f.latitude!=null&&f.longitude!=null?`Geotagged field evidence photo at ${f.latitude.toFixed(4)}, ${f.longitude.toFixed(4)}`:"Geotagged field evidence photo uploaded for this farm plot",loading:"lazy",className:"h-28 w-full object-cover"}):t.jsx("div",{className:"flex h-28 items-center justify-center bg-muted text-xs text-muted-foreground",children:f.file_name}),t.jsxs("div",{className:"space-y-1 p-2",children:[f.description&&t.jsx("div",{className:"line-clamp-2 text-xs",children:f.description}),t.jsx("div",{className:"text-[10px] text-muted-foreground",children:f.latitude!=null&&f.longitude!=null?`${f.latitude.toFixed(4)}, ${f.longitude.toFixed(4)}`:"—"}),t.jsx("div",{className:`inline-block rounded-full px-2 py-0.5 text-[10px] ${f.verified?"bg-emerald-500/10 text-emerald-700 border border-emerald-500/30":"bg-amber-500/10 text-amber-700 border border-amber-500/30"}`,children:f.verified?x.verified:x.pending})]})]},f.id))})]})}function br(){const e=_e(),{lang:r}=L(),{lang:a,id:s}=we(),i=a??r,{userId:l}=K(),[o,c]=y.useState(null),[p,u]=y.useState(!0),[g,x]=y.useState(!1),[h,j]=y.useState(""),[d,f]=y.useState(!1),[_,S]=y.useState(null);y.useEffect(()=>
1{if(p||window.location.hash!=="#boundary")return;const C=document.getElementById("boundary");C&&C.scrollIntoView({behavior:"smooth",block:"start"})},[p]),y.useEffect(()=>{let C=!1;if(!(!l||!s))return(async()=>{const{data:A,error:U}=await k.from("farms").select("id, name, gps_center_lat, gps_center_lng, gps_boundary, size_feddan, created_at, user_id").eq("id",s).maybeSingle();if(!C){if(U||!A||A.user_id!==l){w.warn("farm detail load failed or unauthorized",U),c(null),u(!1);return}c({id:A.id,name:A.name,lat:A.gps_center_lat,lng:A.gps_center_lng,createdAt:A.created_at,boundary:A.gps_boundary??null,sizeFeddan:A.size_feddan}),j(A.name),u(!1)}})(),()=>{C=!0}},[s,l]);const v=y.useMemo(()=>({seo:n({en:"Farm · Zr3i",ar:"مزرعة · زرعي"},r),back:n({en:"Back to workspace",ar:"العودة إلى مساحة العمل"},r),loading:n({en:"Loading…",ar:"جارٍ التحميل…"},r),notFound:n({en:"Farm not found.",ar:"المزرعة غير موجودة."},r),location:n({en:"Location",ar:"الموقع"},r),noLocation:n({en:"Location not set.",ar:"لم يتم تحديد الموقع."},r),locationEditDeferred:n({en:"Editing the saved location will be available later.",ar:"سيكون تعديل الموقع المحفوظ متاحًا لاحقًا."},r),activity:n({en:"Activity",ar:"النشاط"},r),createdAt:n({en:"Farm created",ar:"تم إنشاء المزرعة"},r),edit:n({en:"Edit name",ar:"تعديل الاسم"},r),save:n({en:"Save",ar:"حفظ"},r),saving:n({en:"Saving…",ar:"جارٍ الحفظ…"},r),cancel:n({en:"Cancel",ar:"إلغاء"},r),nameRequired:n({en:"Please enter a name.",ar:"من فضلك أدخل اسمًا."},r),saveFailed:n({en:"Couldn't save. Please try again.",ar:"تعذّر الحفظ. حاول مرة أخرى."},r),viewOnOsm:n({en:"View on OpenStreetMap",ar:"عرض على OpenStreetMap"},r),boundaryTitle:n({en:"Field boundary",ar:"حدود الحقل"},r),boundaryHelp:n({en:"Draw a line around your field. We use it to take your weekly satellite picture and to prepare your carbon paperwork.",ar:"ارسم خطًا حول حقلك. نستخدمه لالتقاط صورتك الأسبوعية من الأقمار الصناعية ولتجهيز أوراق الكربون الخاصة بك."},r),boundarySaved:n({en:"Boundary saved.",ar:"تم حفظ الحدود."},r),boundarySaveFailed:n({en:"Couldn't save the boundary.",ar:"تعذّر حفظ الحدود."},r),lLocate:n({en:"Use my location",ar:"استخدم موقعي"},r),lSave:n({en:"Save boundary",ar:"حفظ الحدود"},r),lClear:n({en:"Clear",ar:"مسح"},r),lEmpty:n({en:"Use the polygon tool on the map to draw your field.",ar:"استخدم أداة المضلع على الخريطة لرسم حقلك."},r),lArea:n({en:"Approximate area:",ar:"المساحة التقريبية:"},r),lHa:n({en:"ha",ar:"هكتار"},r),lFed:n({en:"feddan",ar:"فدان"},r)}),[r]);async function q(){if(o){if(!h.trim()){S(v.nameRequired);return}f(!0),S(null);try{const{error:C}=await k.from("farms").update({name:h.trim()}).eq("id",o.id);
1if(C){w.warn("farm rename failed",C),S(v.saveFailed),f(!1);return}c({...o,name:h.trim()}),x(!1),f(!1)}catch(C){w.error("farm rename threw",C),S(v.saveFailed),f(!1)}}}const[F,E]=y.useState(!1),[T,$]=y.useState(null);async function D(C){if(o){E(!0),$(null);try{const{error:A}=await k.from("farms").update({gps_boundary:C}).eq("id",o.id);if(A)throw w.warn("farm boundary save failed",A),$(v.boundarySaveFailed),A;c({...o,boundary:C}),$(v.boundarySaved)}finally{E(!1)}}}if(p)return t.jsxs("div",{className:"mx-auto max-w-2xl p-6",children:[t.jsx(Q,{title:v.seo,noIndex:!0}),t.jsx("p",{className:"text-sm text-muted-foreground",children:v.loading})]});if(!o)return t.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 p-6",children:[t.jsx(Q,{title:v.seo,noIndex:!0}),t.jsx("p",{className:"text-sm text-muted-foreground",children:v.notFound}),t.jsx("button",{type:"button",onClick:()=>e(`/${i}/dashboard`),className:"inline-flex h-11 items-center rounded-xl border px-4 text-sm font-medium hover:bg-muted",children:v.back})]});const O=o.lat!=null&&o.lng!=null?`${o.lng-.01},${o.lat-.01},${o.lng+.01},${o.lat+.01}`:null;return t.jsxs("div",{className:"mx-auto max-w-2xl space-y-6",children:[t.jsx(Q,{title:`${o.name} · Zr3i`,noIndex:!0}),t.jsxs(ae,{to:`/${i}/dashboard`,className:"text-sm font-medium text-primary hover:underline",children:["← ",v.back]}),t.jsx("header",{className:"space-y-3 rounded-2xl border bg-card p-6 shadow-sm",children:g?t.jsxs("div",{className:"space-y-3",children:[t.jsx("label",{className:"block text-sm font-medium",htmlFor:"farm-name",children:v.edit}),t.jsx("input",{id:"farm-name",type:"text",className:"w-full rounded-xl border bg-background px-4 py-3 text-base",value:h,onChange:C=>j(C.target.value)}),_&&t.jsx("p",{role:"alert",className:"text-sm text-destructive",children:_}),t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{x(!1),j(o.name),S(null)},disabled:d,className:"h-11 rounded-xl border px-4 text-sm font-medium hover:bg-muted disabled:opacity-50",children:v.cancel}),t.jsx("button",{type:"button",onClick:q,disabled:d,className:"h-11 rounded-xl bg-primary px-5 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50",children:d?v.saving:v.save})]})]}):t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsx("h1",{className:"text-2xl font-semibold",children:o.name}),t.jsx("button",{type:"button",onClick:()=>x(!0),className:"h-11 rounded-xl border px-4 text-sm font-medium hover:bg-muted",children:v.edit})]})}),t.jsx("nav",{"aria-label":n({en:"Farm records",ar:"دفتر الأرض"},r),className:"grid grid-cols-2 gap-3 sm:grid-cols-6",children:[{key:"tasks",label:n({en:"Jobs",ar:"الشغل"},r)},{key:"inputs",label:n({en:"What I used",ar:"اللي استخدمته"},r)},{key:"costs",label:n({en:"Money spent",ar:"المصاريف"},r)},{key:"harvest",label:n({en:"Harvest",ar:"الحصاد"},r)},{key:"photos",label:n({en:"Photos",ar:"الصور"},r)},{key:"footprint",label:n({en:"Carbon report",ar:"تقرير الكربون"},r)}].map(C=>t.jsx(ae,{to:`/${i}/farms/${o.id}/${C.key}`,className:"touch-target flex items-center justify-center rounded-xl border px-3 text-center text-sm font-medium hover:bg-muted",children:C.label},C.key))}),t.jsxs("section",{id:"boundary",className:"scroll-mt-20 rounded-2xl border-2 border-primary/40 bg-card p-6 shadow-sm",children:[t.jsx("h2",{className:"text-lg font-semibold",children:v.boundaryTitle}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:v.boundaryHelp}),t.jsxs("div",{className:"mt-4",children:[t.jsx(Ne,{existing:o.boundary,declaredFeddan:o.sizeFeddan,defaultCenter:o.lat!=null&&o.lng!=null?[o.lat,o.lng]:[26.8,30.8],defaultZoom:o.lat!=null?15:6,onSave:D,saving:F,labels:{locate:v.lLocate,save:v.lSave,clear:v.lClear,empty:v.lEmpty,area:v.lArea,hectare:v.lHa,feddan:v.lFed}}),T&&t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:T})]})]}),t.jsxs("section",{className:"rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsx("h2",{className:"text-lg font-semibold",children:v.location}),O?t.jsxs(t.Fragment,{children:[t.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[o.lat?.toFixed(5),", ",o.lng?.toFixed(5)]}),t.jsx("div",{className:"mt-3 overflow-hidden rounded-xl border",children:t.jsx("iframe",{title:"farm map",src:`https://www.openstreetmap.org/export/embed.html?bbox=${O}&layer=mapnik&marker=${o.lat},${o.lng}`,className:"block h-64 w-full",loading:"lazy"})}),t.jsxs("a",{href:`https://www.openstreetmap.org/?mlat=${o.lat}&mlon=${o.lng}#map=15/${o.lat}/${o.lng}`,target:"_blank",rel:"noreferrer noopener",className:"mt-3 inline-block text-xs font-medium text-primary hover:underline",children:[v.viewOnOsm," ↗"]}),t.jsx("p",{className:"mt-3 text-xs text-muted-foreground",children:v.locationEditDeferred})]}):t.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:v.noLocation})]}),t.jsxs("section",{className:"rounded-2xl border bg-card p-6 shadow-sm",children:[t.jsx("h2",{className:"text-lg font-semibold",children:v.activity}),t.jsx("ul",{className:"mt-3 space-y-2",children:t.jsxs("li",{className:"rounded-xl border bg-background px-4 py-3",children:[t.jsx("div",{className:"text-sm font-medium",children:v.createdAt}),o.createdAt&&t.jsx("div",{className:"text-xs text-muted-foreground",children:new Date(o.createdAt).toLocaleStr
1ing(r==="ar"?"ar":"en")})]})})]}),t.jsx(ke,{farmId:o.id,farmName:o.name,boundary:o.boundary}),t.jsxs("details",{className:"rounded-2xl border bg-card shadow-sm",children:[t.jsxs("summary",{className:"flex min-h-[44px] cursor-pointer items-center justify-between gap-3 p-6 text-lg font-semibold",children:[n({en:"Programme progress",ar:"تقدّم البرنامج"},r),t.jsx("span",{className:"text-xs font-normal text-muted-foreground",children:n({en:"Open when you're ready",ar:"افتحها لما تكون جاهز"},r)})]}),t.jsxs("div",{className:"space-y-6 border-t p-6",children:[t.jsx(nt,{farmId:o.id,country:"EG"}),t.jsx(Nt,{farmId:o.id}),t.jsx(ct,{farmId:o.id}),t.jsx(Qt,{farmId:o.id}),t.jsx(ut,{farmId:o.id}),t.jsx(Rt,{farmId:o.id}),t.jsx(zt,{farmId:o.id,annualSequestrationTons:null})]})]})]})}export{br 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.