1import{j as r,u as He,s as ge}from"./app-core-qpl4Fyx7.js";import{a as ne,r as v,j as _e,L as me}from"./vendor-react-Beur_Q69.js";import{R as Ee,a as Re}from"./ReportViewer-o5pfWYjV.js";import{H as ke}from"./heart-CGWlJKgq.js";import{c as De,a as xe,l as U,a4 as Pe,i as Ne,D as ye,p as Ae,X as Te,a5 as $e}from"./index-BLvRqLTp.js";import{C as se}from"./calendar-BTpKfnh1.js";import{C as Ce}from"./clipboard-check-CVfng8aN.js";import{G as ze}from"./git-compare-arrows-DTx4DXZU.js";import{s as Fe}from"./sanitize-DaX-_Ii9.js";import{C as Oe}from"./chevron-left-IEW34QHU.js";import{C as K}from"./chevron-right-BCafP3s2.js";import{P as qe}from"./printer-Cp70ttKp.js";import{M as Ie}from"./maximize-2-avoKjC1S.js";import{L as Me}from"./loader-circle-Yq5vkbXB.js";import{D as Ve}from"./download-Df9s1oZq.js";import{E as Le}from"./eye-D2pLOB5X.js";import{A as Be}from"./arrow-right-DGO6v22B.js";import{E as Ke}from"./ErrorBanner-CHy6Eaul.js";import{S as pe}from"./share-2-BqG8h7j0.js";import{P as Ge}from"./plus-DMwc4ZOL.js";import{F as Ue}from"./file-chart-column-increasing-vEGS9iou.js";import{L as We}from"./link-BcpNGPOo.js";import{M as Ye}from"./mail-DhjWQqLR.js";import"./vendor-zustand-dJuYig_n.js";import"./vendor-supabase-Buf76L6m.js";import"./vendor-analytics-DlhtH1HJ.js";import"./file-text-BfxynmMo.js";import"./globe-DLzBcWyv.js";import"./user-XcXJZESY.js";import"./zoom-out-BJYUQGX5.js";import"./zoom-in-BYIxFLQA.js";import"./vendor-i18n-BcVHTCAN.js";import"./purify.es-DP5U8-sc.js";/** 2 * @license lucide-react v0.468.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const Xe=De("Minimize2",[["polyline",{points:"4 14 10 14 10 20",key:"11kfnr"}],["polyline",{points:"20 10 14 10 14 4",key:"rlmsce"}],["line",{x1:"14",x2:"21",y1:"10",y2:"3",key:"o5lafz"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]),he=[{id:"forest-health",labelKey:"reports.templates.forestHealth",descKey:"reports.templates.forestHealthDesc",icon:r.jsx(ke,{size:16}),color:"var(--green)",frequency:"monthly / quarterly",sections:[{id:"overview",label:"Parcel Overview",required:!0},{id:"health-score",label:"Health Score & Trend",required:!0},{id:"beetle-risk",label:"Beetle Risk Assessment"},{id:"species-mix",label:"Species Composition"},{id:"ndvi",label:"NDVI Analysis"},{id:"detection-summary",label:"Detection Summary"},{id:"recommendations",label:"Recommendations",required:!0},{id:"risk-factors",label:"Risk Factors"},{id:"trend-chart",label:"Historical Trend Chart"}]},{id:"timber-valuation",labelKey:"reports.templates.timberValuation",descKey:"reports.templates.timberValuationDesc",icon:r.jsx(xe,{size:16}),color:"var(--banana)",sections:[{id:"overview",label:"Parcel Overview",required:!0},{id:"volume-species",label:"Volume by Species",required:!0},{id:"price-breakdown",label:"Price Breakdown",required:!0},{id:"market-trend",label:"Market Trend"},{id:"price-history",label:"Price History Chart"},{id:"harvest-rec",label:"Harvest Recommendation"}]},{id:"annual-summary",labelKey:"reports.templates.annualSummary",descKey:"reports.templates.annualSummaryDesc",icon:r.jsx(se,{size:16}),color:"var(--blue)",frequency:"yearly",sections:[{id:"overview",label:"Year Overview",required:!0},{id:"parcel-summary",label:"Parcel Summary",required:!0},{id:"health-trend",label:"Monthly Health Trend"},{id:"timber-value",label:"Timber Valuation"},{id:"carbon",label:"Carbon Offset"},{id:"key-events",label:"Key Events",required:!0},{id:"survey-count",label:"Survey Activity"}]},{id:"compliance",labelKey:"reports.templates.compliance",descKey:"reports.templates.complianceDesc",icon:r.jsx(Ce,{size:16}),color:"var(--eco-air)",sections:[{id:"permit-info",label:"Permit Information",required:!0},{id:"requirements",label:"Requirements Checklist",required:!0},{id:"inspections",label:"Inspection History"},{id:"notes",label:"Notes & Observations"}]},{id:"before-after",labelKey:"reports.templates.beforeAfter",descKey:"reports.templates.beforeAfterDesc",icon:r.jsx(ze,{size:16}),color:"var(--banana)",sections:[{id:"overview",label:"Comparison Overview",required:!0},{id:"health-compare",label:"Health Score Comparison",required:!0},{id:"visual-compare",label:"Visual Comparison"},{id:"detection-diff",label:"Detection Differences"},{id:"recommendations",label:"Updated Recommendations"}]}];function Qe({selected:e,onSelect:a}){const{t:i}=ne();return r.jsxs("div",{className:"space-y-2",children:[r.jsx("span",{className:"text-xs text-[var(--text3)] uppercase tracking-wider block mb-2",children:i("reports.builder.selectTemplate")}),r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:he.map(l=>{const c=e===l.id;return r.jsxs("button",{onClick:()=>a(l.id),className:`text-left p-4 rounded-xl border transition-all ${c?"border-[color-mix(in_srgb,var(--green)_40%,transparent)] bg-[
6color-mix(in_srgb,var(--green)_10%,transparent)]":"border-[var(--border)] bg-[var(--bg2)] hover:border-[var(--text3)]"}`,children:[r.jsxs("div",{className:"flex items-start justify-between",children:[r.jsx("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:`${l.color}15`,color:l.color},children:l.icon}),c&&r.jsx("div",{className:"w-5 h-5 rounded-full bg-[var(--green)] flex items-center justify-center",children:r.jsx(U,{size:12,className:"text-[var(--bg)]"})})]}),r.jsx("h3",{className:`text-sm font-medium mt-3 ${c?"text-[var(--green)]":"text-[var(--text)]"}`,children:i(l.labelKey)}),r.jsx("p",{className:"text-xs text-[var(--text3)] mt-1 line-clamp-2",children:i(l.descKey)}),l.frequency&&r.jsx("span",{className:"inline-block mt-2 text-[9px] font-mono uppercase tracking-wider px-2 py-0.5 rounded-full bg-[var(--bg3)] text-[var(--text3)]",children:l.frequency})]},l.id)})})]})}function Je({templateId:e,selectedSections:a,onToggle:i}){const l=he.find(c=>c.id===e);return l?r.jsxs("div",{children:[r.jsx("span",{className:"text-xs text-[var(--text3)] uppercase tracking-wider block mb-2",children:"Sections to Include"}),r.jsx("div",{className:"space-y-1.5",children:l.sections.map(c=>{const m=a.includes(c.id),s=c.required;return r.jsxs("button",{onClick:()=>!s&&i(c.id),disabled:s,className:`w-full flex items-center gap-3 px-3 py-2 rounded-lg border text-left transition-all text-xs ${m?"border-[color-mix(in_srgb,var(--green)_30%,transparent)] bg-[color-mix(in_srgb,var(--green)_5%,transparent)]":"border-[var(--border)] hover:border-[var(--text3)]"} ${s?"cursor-default":"cursor-pointer"}`,children:[r.jsx("div",{className:`w-4 h-4 rounded flex items-center justify-center flex-shrink-0 border transition-colors ${m?"bg-[var(--green)] border-[var(--green)]":"border-[var(--text3)]"}`,children:m&&r.jsx(U,{size:10,className:"text-[var(--bg)]"})}),r.jsx("span",{className:m?"text-[var(--text)]":"text-[var(--text3)]",children:c.label}),s&&r.jsx("span",{className:"ml-auto text-[9px] font-mono uppercase text-[var(--text3)]",children:"required"})]},c.id)})})]}):null}function Ze({pages:e,title:a}){const[i,l]=v.useState(1),[c,m]=v.useState(!1),s=e.length,t=e.find(o=>o.number===i),u=()=>{const o=window.open("","_blank");o&&(o.document.write(` 7 <!DOCTYPE html> 8 <html> 9 <head> 10 <title>${a??"BeetleSense Report"}</title> 11 <style> 12 @page { size: A4; margin: 12mm; } 13 @media print { .page { page-break-after: always; } .page:last-child { page-break-after: auto; } } 14 body { margin: 0; padding: 0; background: #030d05; color: #e8f0e9; font-family: system-ui, sans-serif; } 15 .page { width: 210mm; min-height: 297mm; padding: 20mm; box-sizing: border-box; position: relative; } 16 .section-title { color: #22c55e; font-size: 14px; font-weight: bold; border-bottom: 1px solid color-mix(in srgb, var(--green) 30%, transparent); padding-bottom: 4px; margin: 16px 0 8px; } 17 .kv { display: flex; gap: 12px; font-size: 11px; line-height: 1.8; } 18 .kv .key { color: #5a6b5c; min-width: 140px; } 19 .kv .val { color: #e8f0e9; } 20 .bullet { padding-left: 16px; position: relative; font-size: 11px; color: #9caa9e; line-height: 1.6; } 21 .bullet::before { content: ''; position: absolute; left: 0; top: 7px; width: 5px; height: 5px; border-radius: 50%; background: #22c55e; } 22 </style> 23 </head> 24 <body> 25 ${e.map(x=>`<div class="page">${x.html}</div>`).join("")} 26 </body> 27 </html> 28 `),o.document.close(),o.focus(),setTimeout(()=>{o.print(),o.close()},500))};return s===0?r.jsx("div",{className:"rounded-xl border border-[var(--border)] bg-[var(--bg2)] p-8 text-center",children:r.jsx("p",{className:"text-sm text-[var(--text3)]",children:"No preview available. Select a template and parcels to generate a preview."})}):r.jsxs("div",{className:`rounded-xl border border-[var(--border)] bg-[var(--bg2)] overflow-hidden ${c?"fixed inset-4 z-50":""}`,children:[r.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-[var(--border)] bg-[var(--bg3)]",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("button",{onClick:()=>l(o=>
28Math.max(1,o-1)),disabled:i<=1,className:"p-1.5 rounded hover:bg-[var(--bg2)] text-[var(--text3)] hover:text-[var(--text)] transition-colors disabled:opacity-30","aria-label":"Previous page",children:r.jsx(Oe,{size:14})}),r.jsxs("span",{className:"text-xs font-mono text-[var(--text2)]",children:[i," / ",s]}),r.jsx("button",{onClick:()=>l(o=>Math.min(s,o+1)),disabled:i>=s,className:"p-1.5 rounded hover:bg-[var(--bg2)] text-[var(--text3)] hover:text-[var(--text)] transition-colors disabled:opacity-30","aria-label":"Next page",children:r.jsx(K,{size:14})})]}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:u,className:"p-1.5 rounded hover:bg-[var(--bg2)] text-[var(--text3)] hover:text-[var(--text)] transition-colors",title:"Print",children:r.jsx(qe,{size:14})}),r.jsx("button",{onClick:()=>m(!c),className:"p-1.5 rounded hover:bg-[var(--bg2)] text-[var(--text3)] hover:text-[var(--text)] transition-colors",title:c?"Exit fullscreen":"Fullscreen",children:c?r.jsx(Xe,{size:14}):r.jsx(Ie,{size:14})})]})]}),r.jsx("div",{className:"overflow-auto bg-[var(--bg)] flex justify-center p-6",style:{height:c?"calc(100% - 44px)":"600px"},children:r.jsx("div",{className:"bg-[var(--bg)] border border-[var(--border)] rounded-sm shadow-md",style:{width:"595px",minHeight:"842px",padding:"40px",fontFamily:"system-ui, sans-serif"},children:t?r.jsx("div",{className:"report-page-content text-[var(--text2)] text-xs leading-relaxed",dangerouslySetInnerHTML:{__html:Fe(t.html)}}):r.jsx("div",{className:"flex items-center justify-center h-full text-[var(--text3)] text-xs",children:"Page not found"})})}),s>1&&r.jsx("div",{className:"flex items-center justify-center gap-1.5 py-2 border-t border-[var(--border)]",children:e.map(o=>r.jsx("button",{onClick:()=>l(o.number),className:`w-2 h-2 rounded-full transition-colors ${i===o.number?"bg-[var(--green)]":"bg-[color-mix(in_srgb,var(--text3)_30%,transparent)] hover:bg-[var(--text3)]"}`,"aria-label":`Go to page ${o.number}`},o.number))})]})}function et(e,a,i){const l=new Date().toLocaleDateString("sv-SE");return[{number:1,html:` 29 <div style="margin-bottom: 20px;"> 30 <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 16px;"> 31 <div style="width: 36px; height: 36px; border-radius: 8px; background: color-mix(in srgb, var(--green) 15%, transparent); display: flex; align-items: center; justify-content: center;"> 32 <span style="color: #22c55e; font-weight: bold; font-size: 18px;">B</span> 33 </div> 34 <div> 35 <div style="font-size: 15px; font-weight: bold; color: #e8f0e9; font-family: Georgia, serif;">BeetleSense.ai</div> 36 <div style="font-size: 9px; color: #5a6b5c;">Forest Intelligence Platform</div> 37 </div> 38 </div> 39 <div style="font-size: 14px; font-weight: bold; color: #e8f0e9; font-family: Georgia, serif;"> 40 Forest Health Report â ${e} 41 </div> 42 <div style="font-size: 9px; color: #5a6b5c; font-family: monospace; margin-top: 2px;">${l}</div> 43 <hr style="border: none; border-top: 1px solid #1a2e1c; margin: 12px 0;" /> 44 </div> 45 46 <div class="section-title">Parcel Overview</div> 47 <div class="kv"><span class="key">Parcel Name</span><span class="val">${e}</span></div> 48 <div class="kv"><span class="key">Health Score</span><span class="val" style="color: ${a>=70?"var(--green)":a>=40?"var(--banana)":"var(--red)"}; font-weight: bold;">${a} / 100</span></div> 49 50 <div class="section-title">Species Composition</div> 51 ${i.map(m=>` 52 <div style="display: flex; align-items: center; gap: 8px; margin: 4px 0;"> 53 <span style="font-size: 10px; color: #5a6b5c; min-width: 60px;">${m.species}</span> 54 <div style="flex: 1; height: 8px; background: #1a2e1c; border-radius: 4px; overflow: hidden;"> 55 <div style="width: ${m.pct}%; height: 100%; background: #22c55e; border-radius: 4px;"></div> 56 </div> 57 <span style="font-size: 9px; font-family: monospace; color: #9caa9e;">${m.pct}%</span> 58 </div> 59 `).join("")} 60 61 <div class="section-title">Recommendations</div> 62 <div class="bullet">Continue regular monitoring with quarterly surveys.</div> 63 <div class="bullet">Inspect spruce-dominant areas for early beetle signs before swarming season.</div> 64 `}]}const V=794,ae=1123,d=48,M=V-d*2,W=18,ue=80,tt=50,Y=d+ue+16,D=ae-d-tt,p={bg:"#08100B",bgCard:"#111A14",green:"#C7FF3D",text:"#
64EEF4E9",text2:"#A5B0A2",text3:"#718074",border:"#29342C",red:"#ef4444",amber:"#fbbf24"};function X(){const e=document.createElement("canvas");e.width=V,e.height=ae;const a=e.getContext("2d");return a.fillStyle=p.bg,a.fillRect(0,0,V,ae),e}function rt(e,a,i,l){const c=new Path2D(Pe);e.save(),e.translate(a,i),e.scale(l/1024,l/1024),e.fillStyle=p.green,e.fill(c,"evenodd"),e.restore()}function Q(e,a,i){e.fillStyle=p.bgCard,ie(e,d,d,40,40,8),e.fill(),rt(e,d+7,d+7,26),e.fillStyle=p.text,e.font='700 18px "Hanken Grotesk", system-ui, sans-serif',e.fillText("BeetleSense",d+50,d+18),e.fillStyle=p.text2,e.font='600 9px "IBM Plex Mono", monospace',e.fillText("FOREST OS · EVIDENCE REPORT",d+50,d+34),e.fillStyle=p.text,e.font='700 16px "Hanken Grotesk", system-ui, sans-serif',e.fillText(a,d,d+65),e.fillStyle=p.text3,e.font="10px monospace",e.textAlign="right",e.fillText(i,V-d,d+65),e.textAlign="left",e.strokeStyle=p.border,e.lineWidth=1,e.beginPath(),e.moveTo(d,d+ue),e.lineTo(V-d,d+ue),e.stroke()}function J(e,a,i){const l=ae-d-20;e.strokeStyle=p.border,e.lineWidth=1,e.beginPath(),e.moveTo(d,l-10),e.lineTo(V-d,l-10),e.stroke(),e.fillStyle=p.text3,e.font="9px monospace",e.fillText("BeetleSense · Evidence for healthier forests",d,l+4),e.textAlign="right",e.fillText(`Page ${a} of ${i}`,V-d,l+4),e.textAlign="left",e.fillStyle=p.text3,e.font="7px system-ui, sans-serif",e.fillText("Decision-support output: verify material findings, sources, and confidence with a qualified forestry professional.",d,l+16)}function w(e,a,i){return e.fillStyle=p.green,e.font='700 13px "Hanken Grotesk", system-ui, sans-serif',e.fillText(i,d,a),e.strokeStyle=p.green,e.globalAlpha=.3,e.lineWidth=1,e.beginPath(),e.moveTo(d,a+5),e.lineTo(V-d,a+5),e.stroke(),e.globalAlpha=1,a+22}function f(e,a,i,l){return e.fillStyle=p.text3,e.font="10px system-ui, sans-serif",e.fillText(i,d,a),e.fillStyle=p.text,e.font="10px system-ui, sans-serif",e.fillText(l,d+160,a),a+W}function fe(e,a,i,l){e.fillStyle=l?.color??p.text2,e.font=l?.font??"10px system-ui, sans-serif";const c=d+(l?.indent??0),m=i.split(" ");let s="";const t=M-(l?.indent??0);for(const u of m){const o=s+(s?" ":"")+u;e.measureText(o).width>t&&s?(e.fillText(s,c,a),s=u,a+=W):s=o}return s&&(e.fillText(s,c,a),a+=W),a}function Se(e,a,i,l){return e.fillStyle=l??p.green,e.beginPath(),e.arc(d+6,a-3,2.5,0,Math.PI*2),e.fill(),fe(e,a,i,{indent:16})}function Z(e,a,i,l,c){e.fillStyle=p.bgCard,e.strokeStyle=p.border,e.lineWidth=1,ie(e,a,i,l,c,6),e.fill(),e.stroke()}function be(e,a,i,l,c,m){if(Z(e,a,i,l,c),m.length===0)return;const s=12,t=a+s+40,u=l-s*2-40,o=Math.min(16,(c-s*2)/m.length-4),x=Math.max(...m.map(g=>g.value),1);m.forEach((g,h)=>{const H=i+s+h*(o+4),S=g.value/x*u;e.fillStyle=p.text3,e.font="8px system-ui, sans-serif",e.textAlign="right",e.fillText(g.label,t-6,H+o/2+3),e.textAlign="left",e.fillStyle=g.color??p.green,e.globalAlpha=.8,ie(e,t,H,Math.max(S,2),o,3),e.fill(),e.globalAlpha=1,e.fillStyle=p.text2,e.font="8px monospace",e.fillText(String(g.value),t+S+6,H+o/2+3)})}function ve(e,a,i,l,c,m,s){if(Z(e,a,i,l,c),m.length<2)return;const t=20,u=a+t+20,o=l-t*2-20,x=i+t,g=c-t*2-12,h=Math.max(...m.map(k=>k.value),1),H=Math.min(...m.map(k=>k.value),0),S=h-H||1,O=p.green;e.strokeStyle=p.border,e.lineWidth=.5;for(let k=0;k<=4;k++){const R=x+g/4*k;e.beginPath(),e.moveTo(u,R),e.lineTo(u+o,R),e.stroke();const P=h-S/4*k;e.fillStyle=p.text3,e.font="7px monospace",e.textAlign="right",e.fillText(P.toFixed(0),u-4,R+3),e.textAlign="left"}e.beginPath(),e.strokeStyle=O,e.lineWidth=2,m.forEach((k,R)=>{const P=u+R/(m.length-1)*o,q=x+g-(k.value-H)/S*g;R===0?e.moveTo(P,q):e.lineTo(P,q)}),e.stroke(),e.globalAlpha=.1,e.fillStyle=O,e.lineTo(u+o,x+g),e.lineTo(u,x+g),e.closePath(),e.fill(),e.globalAlpha=1;const z=[0,Math.floor(m.length/2),m.length-1];e.fillStyle=p.text3,e.font="7px monospace",z.forEach(k=>{if(k<m.length){const R=u+k/(m.length-1)*o;e.textAlign="center",e.fillText(m[k].label,R,x+g+12)}}),e.textAlign="left"}function ie(e,a,i,l,c,m){e.beginPath(),e.moveTo(a+m,i),e.lineTo(a+l-m,i),e.quadraticCurveTo(a+l,i,a+l,i+m),e.lineTo(a+l,i+c-m),e.quadraticCurveTo(a+l,i+c,a+l-m,i+c),e.lineTo(a+m,i+c),e.quadraticCurveTo(a,i+c,a,i+c-m),e.lineTo(a,i+m),e.quadraticCurveTo(a,i,a+m,i),e.closePath()}function st(e,a,i,l,c){e.font="9px system-ui, sans-serif";const m=e.measureText(l).width,s=8;e.fillStyle=c,e.globalAlpha=.15,ie(e,a,i-10,m+s*2,16,8),e.fill(),e.globalAlpha=1,e.fillStyle=c,e.fillText(l,a+s,i)}function at(e){switch(e){case"low":return p.green;case"medium":return p.amber;case"high":return p.red;case"critical":return p.red;default:return p.text3}}function F(e){if(!e)return new Date().toLocaleDateString("sv-SE");try{return new Date(e).toLocaleDateString("sv-SE")}catch{return e}}
64function G(e){return e.toLocaleString("sv-SE",{style:"currency",currency:"SEK",maximumFractionDigits:0})}async function le(e){const a=[];for(const l of e)a.push(l.toDataURL("image/png",1));const i=`<!DOCTYPE html> 65<html> 66<head> 67<meta charset="utf-8"> 68<title>BeetleSense Report</title> 69<style> 70@page { size: A4; margin: 0; } 71@media print { body { margin: 0; } .page { page-break-after: always; } .page:last-child { page-break-after: auto; } } 72body { margin: 0; padding: 0; background: #08100B; } 73.page { width: 210mm; height: 297mm; position: relative; overflow: hidden; } 74.page img { width: 100%; height: 100%; object-fit: contain; } 75</style> 76</head> 77<body> 78${a.map(l=>`<div class="page"><img src="${l}" /></div>`).join(` 79`)} 80</body> 81</html>`;return new Blob([i],{type:"text/html"})}async function je(e,a){const i=[],l=F(),c=`Forest Health Report â ${e.parcelName}`;a?.(10);const m=X(),s=m.getContext("2d");Q(s,c,l);let t=Y;t=w(s,t,"Parcel Overview"),t=f(s,t,"Parcel Name",e.parcelName),t=f(s,t,"Municipality",e.municipality),t=f(s,t,"Area",`${e.areaHectares.toFixed(1)} hectares`),t=f(s,t,"Last Survey",F(e.lastSurveyDate)),t=f(s,t,"Trees Scanned",e.treesScanned.toLocaleString()),t+=8,t=w(s,t,"Species Composition"),be(s,d,t,M,Math.max(80,e.speciesMix.length*20+24),e.speciesMix.map(S=>({label:S.species,value:S.pct,color:p.green}))),t+=Math.max(80,e.speciesMix.length*20+24)+16,t=w(s,t,"Health Assessment");const u=e.healthScore>=70?p.green:e.healthScore>=40?p.amber:p.red;Z(s,d,t,M/3-8,60),s.fillStyle=u,s.font="bold 24px monospace",s.fillText(`${e.healthScore}`,d+16,t+30),s.fillStyle=p.text3,s.font="9px system-ui, sans-serif",s.fillText("Health Score",d+16,t+48),Z(s,d+M/3,t,M/3-8,60);const o=e.healthTrend.charAt(0).toUpperCase()+e.healthTrend.slice(1);s.fillStyle=p.text,s.font="bold 14px system-ui, sans-serif",s.fillText(o,d+M/3+16,t+30),s.fillStyle=p.text3,s.font="9px system-ui, sans-serif",s.fillText("Trend",d+M/3+16,t+48),Z(s,d+M/3*2,t,M/3,60);const x=at(e.beetleRisk);s.fillStyle=x,s.font="bold 14px system-ui, sans-serif",s.fillText(e.beetleRisk.toUpperCase(),d+M/3*2+16,t+30),s.fillStyle=p.text3,s.font="9px system-ui, sans-serif",s.fillText("Beetle Risk",d+M/3*2+16,t+48),t+=80,t=w(s,t,"Detection Summary"),t=f(s,t,"Infected Trees",`${e.infectedTrees} (${(e.infectedTrees/Math.max(e.treesScanned,1)*100).toFixed(1)}%)`),t=f(s,t,"Dead Trees",`${e.deadTrees}`),t=f(s,t,"NDVI Average",e.ndviAvg.toFixed(2)),t=f(s,t,"Timber Volume",`${e.timberVolumeM3.toLocaleString()} m3`),t=f(s,t,"Estimated Value",G(e.timberValueSEK)),t=f(s,t,"Carbon Sequestration",`${e.carbonTonsCO2.toFixed(1)} tonnes CO2`),J(s,1,2),i.push(m),a?.(50);const g=X(),h=g.getContext("2d");if(Q(h,c,l),t=Y,e.historicalScores.length>1&&(t=w(h,t,"Health Score Trend (12 months)"),ve(h,d,t,M,140,e.historicalScores.map(S=>({label:S.month,value:S.score}))),t+=160),e.riskFactors.length>0){t=w(h,t,"Risk Factors");for(const S of e.riskFactors)if(t=Se(h,t,S,p.amber),t>D-40)break;t+=8}if(e.recommendations.length>0){t=w(h,t,"Recommendations");for(const S of e.recommendations)if(t=Se(h,t,S,p.green),t>D-40)break}J(h,2,2),i.push(g),a?.(90);const H=await le(i);return a?.(100),H}async function nt(e,a){const i=[],l=F(),c=`Timber Valuation Report â ${e.parcelName}`;a?.(10);const m=X(),s=m.getContext("2d");Q(s,c,l);let t=Y;t=w(s,t,"Parcel Information"),t=f(s,t,"Parcel Name",e.parcelName),t=f(s,t,"Municipality",e.municipality),t=f(s,t,"Area",`${e.areaHectares.toFixed(1)} hectares`),t=f(s,t,"Total Volume",`${e.totalVolume.toLocaleString()} m3fub`),t=f(s,t,"Estimated Total Value",G(e.totalValue)),t=f(s,t,"Market Trend",e.marketTrend.charAt(0).toUpperCase()+e.marketTrend.slice(1)),t+=8,a?.(30),t=w(s,t,"Volume by Species"),be(s,d,t,M,Math.max(80,e.volumeBySpecies.length*22+24),e.volumeBySpecies.map(u=>({label:u.species,value:u.m3,color:p.green}))),t+=Math.max(80,e.volumeBySpecies.length*22+24)+16,t=w(s,t,"Valuation Breakdown"),s.fillStyle=p.text3,s.font="bold 9px system-ui, sans-serif",s.fillText("Species",d,t),s.fillText("Volume (m3)",d+180,t),s.fillText("Price/m3",d+300,t),s.fillText("Value",d+420,t),t+=14;for(const u of e.volumeBySpecies)s.fillStyle=p.text,s.font="10px system-ui, sans-serif",s.fillText(u.species,d,t),s.font="10px monospace",s.fillText(u.m3.toLocaleStr
81ing(),d+180,t),s.fillText(G(u.pricePerM3),d+300,t),s.fillText(G(u.m3*u.pricePerM3),d+420,t),t+=W;return t+=8,e.priceHistory.length>1&&(t=w(s,t,"Price Trend (12 months)"),ve(s,d,t,M,140,e.priceHistory.map(u=>({label:u.month,value:u.price}))),t+=160),a?.(70),t<D-60&&(t=w(s,t,"Harvest Recommendation"),t=fe(s,t,e.harvestRecommendation)),J(s,1,1),i.push(m),a?.(100),le(i)}async function it(e,a){const i=[],l=F(),c=`Compliance Report â ${e.parcelName}`;a?.(10);const m=X(),s=m.getContext("2d");Q(s,c,l);let t=Y;t=w(s,t,"Permit Information"),t=f(s,t,"Permit ID",e.permitId),t=f(s,t,"Type",e.permitType),t=f(s,t,"Parcel",e.parcelName),t=f(s,t,"Municipality",e.municipality),t=f(s,t,"Issued",F(e.issuedDate)),t=f(s,t,"Expires",F(e.expiryDate)),t+=4;const u=e.status==="active"?p.green:e.status==="pending"?p.amber:p.red;st(s,d+160,t,e.status.toUpperCase(),u),t=f(s,t,"Status",""),t+=12,a?.(30),t=w(s,t,"Requirements Checklist");for(const o of e.requirements){const x=o.met?"â":"â",g=o.met?p.green:p.red;if(s.fillStyle=g,s.font="bold 12px system-ui, sans-serif",s.fillText(x,d+4,t),s.fillStyle=p.text,s.font="10px system-ui, sans-serif",s.fillText(o.requirement,d+20,t),t+=W,t>D-80)break}if(t+=8,a?.(60),e.inspections.length>0&&t<D-100){t=w(s,t,"Inspection History");for(const o of e.inspections)if(t=f(s,t,F(o.date),`${o.result} (${o.inspector})`),t>D-60)break;t+=8}return e.notes&&t<D-40&&(t=w(s,t,"Notes"),t=fe(s,t,e.notes)),J(s,1,1),i.push(m),a?.(100),le(i)}async function lt(e,a){const i=[],l=F(),c=`Annual Summary ${e.year} â ${e.ownerName}`;a?.(10);const m=X(),s=m.getContext("2d");Q(s,c,l);let t=Y;t=w(s,t,"Annual Overview"),t=f(s,t,"Year",String(e.year)),t=f(s,t,"Forest Owner",e.ownerName),t=f(s,t,"Total Area",`${e.totalArea.toFixed(1)} hectares`),t=f(s,t,"Number of Parcels",String(e.parcels.length)),t=f(s,t,"Total Surveys",String(e.totalSurveys)),t=f(s,t,"Avg Health Score",`${e.avgHealthScore.toFixed(0)} / 100`),t=f(s,t,"Total Timber Value",G(e.totalTimberValue)),t=f(s,t,"Carbon Offset",`${e.carbonOffset.toFixed(1)} tonnes CO2`),t+=12,a?.(30),e.monthlyScores.length>1&&(t=w(s,t,"Monthly Health Score"),ve(s,d,t,M,140,e.monthlyScores.map(x=>({label:x.month,value:x.score}))),t+=160),t<D-120&&(t=w(s,t,"Parcel Overview"),be(s,d,t,M,Math.min(160,e.parcels.length*22+24),e.parcels.map(x=>({label:x.name,value:x.healthScore,color:x.healthScore>=70?p.green:x.healthScore>=40?p.amber:p.red})))),J(s,1,2),i.push(m),a?.(50);const u=X(),o=u.getContext("2d");Q(o,c,l),t=Y,t=w(o,t,"Parcel Details"),o.fillStyle=p.text3,o.font="bold 9px system-ui, sans-serif",o.fillText("Parcel",d,t),o.fillText("Area (ha)",d+160,t),o.fillText("Health",d+260,t),o.fillText("Value (SEK)",d+360,t),o.fillText("Surveys",d+500,t),t+=14;for(const x of e.parcels){o.fillStyle=p.text,o.font="10px system-ui, sans-serif",o.fillText(x.name,d,t),o.font="10px monospace",o.fillText(x.areaHectares.toFixed(1),d+160,t);const g=x.healthScore;if(o.fillStyle=g>=70?p.green:g>=40?p.amber:p.red,o.fillText(String(g),d+260,t),o.fillStyle=p.text,o.fillText(G(x.timberValueSEK),d+360,t),o.fillText(String(x.surveysCompleted),d+500,t),t+=W,t>D-120)break}if(t+=12,a?.(70),e.keyEvents.length>0&&t<D-60){t=w(o,t,"Key Events");for(const x of e.keyEvents)if(t=f(o,t,F(x.date),x.description),t>D-40)break}return J(o,2,2),i.push(u),a?.(100),le(i)}function ot(e,a){const i=URL.createObjectURL(e),l=document.createElement("a");l.href=i,l.download=a,document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),5e3)}const I=["template","parcels","sections","dates","preview"];function ct({onClose:e}){const{t:a}=ne(),[i,l]=v.useState("template"),[c,m]=v.useState(null),[s,t]=v.useState([]),[u,o]=v.useState([]),[x,g]=v.useState(()=>{const n=new Date;return n.setMonth(n.getMonth()-3),n.toISOString().slice(0,10)}),[h,H]=v.useState(()=>new Date().toISOString().slice(0,10)),[S,O]=v.useState(!1),[z,k]=v.useState(0),[R,P]=v.useState(null),[q,ee]=v.useState([]),j=v.useMemo(()=>Ne()?ye.map(n=>({id:n.id,name:n.name,areaHectares:n.area_hectares,municipality:n.municipality,healthScore:n.status==="healthy"?82:n.status==="at_risk"?55:n.status==="infested"?28:50,speciesMix:n.species_mix})):ye.map(n=>({id:n.id,name:n.name,areaHectares:n.area_hectares,municipality:n.municipality,healthScore:70,speciesMix:n.species_mix})),[]),N=I.indexOf(i),_=N>0,B=v.useMemo(()=>{switch(i){case"template":return c!==null;case"parcels":return s.length>0;case"sections":return u.length>0;case"dates":return x&&h;case"preview":return!0;default:return!1}},[i,c,s,u,x,h]),oe=v.useCallback(n=>{m(n);const b=he.find(E=>E.id===n);b&&o(b.sections.map(E=>E.id))},[]),ce=v.useCallback(n=>{t(b=>b.includes(n)?b.filter(E=>E!==n):[...b,n])},[]),de=v.useCallback(n=>{o(b=>b.includes(n)?b.filter(E=>E!==n):[...b,n])},[]),te=v.useCallback(()=>{const n=I.indexOf(i);if(n<I.length-1){const b=I[n+1];if(l(b),b==="preview"){const E=j.find(L=>
81s.includes(L.id));E&&ee(et(E.name,E.healthScore,E.speciesMix))}}},[i,j,s]),re=v.useCallback(()=>{const n=I.indexOf(i);n>0&&l(I[n-1])},[i]),C=v.useCallback(async()=>{if(!(!c||s.length===0)){O(!0),k(0),P(null);try{const n=j.find(T=>s.includes(T.id));if(!n)throw new Error("No parcel selected");let b;const E=`beetlesense_${c}_${n.name.toLowerCase().replace(/\s+/g,"_")}_${h}.html`,L=T=>k(T);switch(c){case"forest-health":{const T={parcelId:n.id,parcelName:n.name,municipality:n.municipality,areaHectares:n.areaHectares,speciesMix:n.speciesMix,healthScore:n.healthScore,healthTrend:"stable",beetleRisk:n.healthScore>=70?"low":n.healthScore>=40?"medium":"high",lastSurveyDate:h,treesScanned:Math.round(n.areaHectares*120),infectedTrees:Math.round(n.areaHectares*120*(1-n.healthScore/100)*.3),deadTrees:Math.round(n.areaHectares*2),timberVolumeM3:Math.round(n.areaHectares*180),timberValueSEK:Math.round(n.areaHectares*180*550),carbonTonsCO2:Math.round(n.areaHectares*12.5),ndviAvg:.62+n.healthScore/100*.25,recommendations:["Continue regular monitoring with quarterly drone surveys.","Inspect spruce-dominant areas for early beetle signs before May swarming.","Consider sanitary felling of confirmed infested trees within 4 weeks.","Install pheromone traps along southern edges of spruce stands."],riskFactors:["Spruce dominance (>60%) increases bark beetle vulnerability.","Adjacent clear-cuts detected within 2 km may drive beetle migration.","Dry weather forecast for April-May increases swarming probability."],historicalScores:Array.from({length:12},(A,y)=>({month:new Date(2025,3+y).toLocaleDateString("sv-SE",{month:"short"}),score:Math.round(65+Math.random()*20+Math.sin(y/3)*8)}))};b=await je(T,L);break}case"timber-valuation":{const T={parcelId:n.id,parcelName:n.name,municipality:n.municipality,areaHectares:n.areaHectares,speciesMix:n.speciesMix,volumeBySpecies:n.speciesMix.map(A=>({species:A.species,m3:Math.round(n.areaHectares*180*A.pct/100),pricePerM3:A.species==="Spruce"?580:A.species==="Pine"?620:A.species==="Oak"?1200:380})),totalVolume:Math.round(n.areaHectares*180),totalValue:Math.round(n.areaHectares*180*550),marketTrend:"stable",harvestRecommendation:"Market conditions are stable. Spruce timber prices show slight upward pressure due to reduced supply from storm-damaged areas. Consider a selective harvest in Q3 2026 when demand typically peaks for construction-grade timber.",priceHistory:Array.from({length:12},(A,y)=>({month:new Date(2025,3+y).toLocaleDateString("sv-SE",{month:"short"}),price:Math.round(520+Math.random()*80+y*3)}))};b=await nt(T,L);break}case"compliance":{const T={permitId:`SK-${n.municipality.substring(0,3).toUpperCase()}-2026-${Math.floor(1e3+Math.random()*9e3)}`,permitType:"Avverkningsanmälan (Felling Notification)",parcelName:n.name,municipality:n.municipality,issuedDate:x,expiryDate:new Date(new Date(h).getTime()+31536e6).toISOString().slice(0,10),status:"active",requirements:[{requirement:"Notify Skogsstyrelsen 6 weeks before felling",met:!0},{requirement:"Retain at least 10 seed trees per hectare",met:!0},{requirement:"Buffer zone of 10 m along watercourses",met:!0},{requirement:"Mark key biotope boundaries",met:!1},{requirement:"Complete regeneration within 3 years",met:!1}],inspections:[{date:x,result:"Approved with conditions",inspector:"K. Lindqvist"}],notes:"The parcel includes a registered key biotope (nyckelbiotop) in the northeastern corner. This area must be excluded from any harvesting activity. Regeneration plan required before felling commences."};b=await it(T,L);break}case"annual-summary":{const T=j.filter(y=>s.includes(y.id)),A={year:new Date(h).getFullYear(),ownerName:"Forest Owner",parcels:T.map(y=>({name:y.name,areaHectares:y.areaHectares,healthScore:y.healthScore,timberValueSEK:Math.round(y.areaHectares*180*550),surveysCompleted:Math.floor(1+Math.random()*4)})),totalArea:T.reduce((y,$)=>y+$.areaHectares,0),avgHealthScore:Math.round(T.reduce((y,$)=>y+$.healthScore,0)/T.length),totalTimberValue:T.reduce((y,$)=>y+Math.round($.areaHectares*180*550),0),totalSurveys:T.length*3,carbonOffset:T.reduce((y,$)=>y+$.areaHectares*12.5,0),keyEvents:[{date:`${new Date(h).getFullYear()}-04-15`,description:"Spring beetle assessment completed across all parcels"},{date:`${new Date(h).getFullYear()}-07-22`,description:"Summer drone survey detected bark beetle activity in Granudden"},{date:`${new Date(h).getFullYear()}-09-10`,description:"Sanitary felling completed in affected areas"},{date:`${new Date(h).getFullYear()}-11-30`,description:"Annual compliance review passed"}
81],monthlyScores:Array.from({length:12},(y,$)=>({month:new Date(new Date(h).getFullYear(),$).toLocaleDateString("sv-SE",{month:"short"}),score:Math.round(60+Math.random()*25+Math.sin($/2)*5)}))};b=await lt(A,L);break}case"before-after":{const T={parcelId:n.id,parcelName:`${n.name} (Comparison)`,municipality:n.municipality,areaHectares:n.areaHectares,speciesMix:n.speciesMix,healthScore:n.healthScore,healthTrend:"improving",beetleRisk:"medium",lastSurveyDate:h,treesScanned:Math.round(n.areaHectares*120),infectedTrees:Math.round(n.areaHectares*5),deadTrees:Math.round(n.areaHectares*1),timberVolumeM3:Math.round(n.areaHectares*180),timberValueSEK:Math.round(n.areaHectares*180*550),carbonTonsCO2:Math.round(n.areaHectares*12.5),ndviAvg:.72,recommendations:["Health improvement trend confirmed after sanitary measures.","Continue monitoring previously affected zones for re-infestation."],riskFactors:["Some residual beetle population in adjacent stands."],historicalScores:Array.from({length:12},(A,y)=>({month:new Date(2025,3+y).toLocaleDateString("sv-SE",{month:"short"}),score:Math.round(45+y*3+Math.random()*5)}))};b=await je(T,L);break}default:throw new Error("Unknown template")}ot(b,E)}catch(n){P(n instanceof Error?n.message:"Report generation failed")}finally{O(!1)}}},[c,s,j,x,h]);return r.jsxs("div",{className:"space-y-6",children:[r.jsx("div",{className:"flex items-center gap-1",children:I.map((n,b)=>r.jsxs("div",{className:"flex items-center",children:[r.jsxs("button",{onClick:()=>b<=N&&l(n),className:`flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${n===i?"bg-[color-mix(in_srgb,var(--green)_10%,transparent)] text-[var(--green)]":b<N?"text-[var(--text2)] hover:text-[var(--text)]":"text-[var(--text3)]"}`,children:[r.jsx("span",{className:`w-5 h-5 rounded-full flex items-center justify-center text-[9px] font-bold ${b<N?"bg-[var(--green)] text-[var(--bg)]":n===i?"bg-[color-mix(in_srgb,var(--green)_20%,transparent)] text-[var(--green)]":"bg-[var(--bg3)] text-[var(--text3)]"}`,children:b<N?r.jsx(U,{size:10}):b+1}),r.jsx("span",{className:"hidden sm:inline capitalize",children:n})]}),b<I.length-1&&r.jsx("div",{className:`w-6 h-px mx-1 ${b<N?"bg-[var(--green)]":"bg-[var(--border)]"}`})]},n))}),r.jsxs("div",{className:"min-h-[300px]",children:[i==="template"&&r.jsx(Qe,{selected:c,onSelect:oe}),i==="parcels"&&r.jsxs("div",{children:[r.jsx("span",{className:"text-xs text-[var(--text3)] uppercase tracking-wider block mb-2",children:a("reports.builder.selectParcels")}),r.jsx("div",{className:"space-y-2",children:j.map(n=>{const b=s.includes(n.id);return r.jsxs("button",{onClick:()=>ce(n.id),className:`w-full flex items-center gap-3 p-3 rounded-xl border text-left transition-all ${b?"border-[color-mix(in_srgb,var(--green)_40%,transparent)] bg-[color-mix(in_srgb,var(--green)_10%,transparent)]":"border-[var(--border)] bg-[var(--bg2)] hover:border-[var(--text3)]"}`,children:[r.jsx("div",{className:`w-4 h-4 rounded flex items-center justify-center flex-shrink-0 border transition-colors ${b?"bg-[var(--green)] border-[var(--green)]":"border-[var(--text3)]"}`,children:b&&r.jsx(U,{size:10,className:"text-[var(--bg)]"})}),r.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center bg-[color-mix(in_srgb,var(--green)_10%,transparent)] flex-shrink-0",children:r.jsx(xe,{size:14,className:"text-[var(--green)]"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:`text-sm font-medium ${b?"text-[var(--green)]":"text-[var(--text)]"}`,children:n.name}),r.jsxs("p",{className:"text-xs text-[var(--text3)]",children:[n.municipality," · ",n.areaHectares," ha"]})]}),r.jsx("span",{className:`text-xs font-mono ${n.healthScore>=70?"text-[var(--green)]":n.healthScore>=40?"text-[var(--banana)]":"text-[var(--red)]"}`,children:n.healthScore})]},n.id)})})]}),i==="sections"&&c&&r.jsx(Je,{templateId:c,selectedSections:u,onToggle:de}),i==="dates"&&r.jsxs("div",{children:[r.jsx("span",{className:"text-xs text-[var(--text3)] uppercase tracking-wider block mb-3",children:a("reports.builder.dateRange")}),r.jsxs("div",{className:"grid grid-cols-2 gap-4 max-w-md",children:[r.jsxs("div",{children:[r.jsx("label",{htmlFor:"reportbuilder-f1",className:"text-xs text-[var(--text3)] block mb-1",children:"From"}),r.jsxs("div",{className:"relative",children:[r.jsx(se,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text3)]"}),r.jsx("input",{id:"reportbuilder-f1",type:"date",value:x,onChange:n=>g(n.target.value),className:"w-full pl-9 pr-3 py-2.5 rounded-lg border border-[var(--border)] bg-[var(--bg2)] text-xs text-[var(--text)] focu
81s:outline-none focus:border-[var(--green)] [color-scheme:dark]"})]})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"reportbuilder-f2",className:"text-xs text-[var(--text3)] block mb-1",children:"To"}),r.jsxs("div",{className:"relative",children:[r.jsx(se,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text3)]"}),r.jsx("input",{id:"reportbuilder-f2",type:"date",value:h,onChange:n=>H(n.target.value),className:"w-full pl-9 pr-3 py-2.5 rounded-lg border border-[var(--border)] bg-[var(--bg2)] text-xs text-[var(--text)] focus:outline-none focus:border-[var(--green)] [color-scheme:dark]"})]})]})]})]}),i==="preview"&&r.jsx("div",{className:"space-y-4",children:r.jsx(Ze,{pages:q,title:c?`BeetleSense ${c} Report`:void 0})})]}),R&&r.jsx("div",{className:"p-3 rounded-lg bg-[color-mix(in_srgb,var(--red)_10%,transparent)] border border-[color-mix(in_srgb,var(--red)_30%,transparent)] text-xs text-[var(--red)]",children:R}),r.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-[var(--border)]",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[e&&r.jsx("button",{onClick:e,className:"px-4 py-2 rounded-lg text-xs font-medium text-[var(--text3)] hover:text-[var(--text)] transition-colors",children:a("common.cancel")}),_&&r.jsxs("button",{onClick:re,className:"flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-medium text-[var(--text2)] hover:text-[var(--text)] border border-[var(--border)] hover:border-[var(--text3)] transition-colors",children:[r.jsx(Ae,{size:12}),a("common.back")]})]}),r.jsx("div",{children:i==="preview"?r.jsx("button",{onClick:C,disabled:S,className:"flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-semibold bg-[var(--green)] text-[var(--bg)] hover:brightness-110 transition disabled:opacity-50",children:S?r.jsxs(r.Fragment,{children:[r.jsx(Me,{size:16,className:"animate-spin"}),r.jsxs("span",{children:[a("reports.builder.generating")," ",z,"%"]})]}):r.jsxs(r.Fragment,{children:[r.jsx(Ve,{size:16}),a("reports.builder.generatePdf")]})}):r.jsx("button",{onClick:te,disabled:!B,className:"flex items-center gap-1.5 px-5 py-2.5 rounded-xl text-sm font-semibold bg-[var(--green)] text-[var(--bg)] hover:brightness-110 transition disabled:opacity-30",children:i==="dates"?r.jsxs(r.Fragment,{children:[r.jsx(Le,{size:14}),a("reports.builder.previewReport")]}):r.jsxs(r.Fragment,{children:[a("common.next"),r.jsx(Be,{size:14})]})})})]})]})}const dt=[{id:"health",labelKey:"reports.quick.forestHealth",icon:ke,color:"var(--green)",template:"forest-health"},{id:"timber",labelKey:"reports.quick.timberValue",icon:xe,color:"var(--banana)",template:"timber-valuation"},{id:"annual",labelKey:"reports.quick.annualSummary",icon:se,color:"var(--blue)",template:"annual-summary"},{id:"compliance",labelKey:"reports.quick.compliance",icon:Ce,color:"var(--eco-air)",template:"compliance"}];function we({report:e,onClose:a}){const{t:i}=ne(),[l,c]=v.useState(""),[m,s]=v.useState(!1),[t,u]=v.useState(!1),o=`${window.location.origin}/owner/reports?view=${e.id}`,x=()=>{navigator.clipboard.writeText(o).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)})},g=()=>{l&&(u(!0),setTimeout(()=>{u(!1),a()},1500))};return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-[color-mix(in_srgb,var(--bg)_40%,transparent)]",children:r.jsxs("div",{className:"w-full max-w-sm rounded-2xl border border-[var(--border)] bg-[var(--bg2)] overflow-hidden",children:[r.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-[var(--border)]",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(pe,{size:14,className:"text-[var(--green)]"}),r.jsx("h3",{className:"text-sm font-sans font-bold text-[var(--text)]",children:i("reports.share.title")})]}),r.jsx("button",{onClick:a,className:"text-[var(--text3)] hover:text-[var(--text)] transition-colors",children:r.jsx(Te,{size:14})})]}),r.jsxs("div",{className:"p-5 space-y-4",children:[r.jsx("p",{className:"text-xs text-[var(--text3)]",children:e.title}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"reportspage-f1",className:"text-xs text-[var(--text3)] uppercase tracking-wider block mb-1",children:i("reports.share.copyLink")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{id:"reportspage-f1",readOnly:!0,value:o,className:"flex-1 px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg)] text-xs text-[var(--text2)] font-mono truncate"}),r.jsx("button",{onClick:x,className:`px-3 py-2 rounded-lg text-xs font-medium transition-colors ${m?"bg-[color-mix(in_srgb,var(--green)_10%,transparent)] text-[var(--green)]":"bg-[var(--bg3)] text-[var(--text2)] hover:text-[var(--text)]"}`,children:m?r.jsx(U,{size:14}):r.jsx(We,{size:14})})]})]}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"reportspage-f2",className:"text-xs text-[var(--text3)] uppercase tracking-wider block mb-1",children:i("reports.share.sendEmail")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{id:"reportspage-f2",type:"email",value:l,onCh
81ange:h=>c(h.target.value),placeholder:"[email protected]",className:"flex-1 px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--bg)] text-xs text-[var(--text)] placeholder:text-[var(--text3)] focus:outline-none focus:border-[var(--green)]"}),r.jsx("button",{onClick:g,disabled:!l||t,className:"px-4 py-2 rounded-lg text-xs font-semibold bg-[var(--green)] text-[var(--bg)] hover:brightness-110 transition disabled:opacity-40",children:t?r.jsx(U,{size:14}):r.jsx(Ye,{size:14})})]})]})]})]})})}function Bt(){const{t:e}=ne(),{profile:a}=He(),[i,l]=_e(),[c,m]=v.useState([]),[s,t]=v.useState(!0),[u,o]=v.useState(null),[x,g]=v.useState(!1),[h,H]=v.useState(null),[S,O]=v.useState(null),z=i.get("view"),k=i.get("action");v.useEffect(()=>{k==="builder"&&g(!0)},[k]),v.useEffect(()=>{if(!a)return;async function j(){if(O(null),Ne()){const N=$e.map(_=>({id:_.id,title:_.title,type:_.type==="valuation"?"valuation":"standard",parcel_name:_.parcel_name,created_at:_.created_at,language:"en",status:_.status==="ready"?"generated":"draft"}));if(m(N),z){const _=N.find(B=>B.id===z);_&&o(_)}t(!1);return}try{const[N,_]=await Promise.all([ge.from("reports").select("id, title, report_type, parcel_name, created_at, language, status, pdf_url, inspector_name").eq("owner_id",a.id).order("created_at",{ascending:!1}),ge.from("shared_reports").select("report:reports(id, title, report_type, parcel_name, created_at, language, status, pdf_url, inspector_name)").eq("shared_with_email",a.email).order("shared_at",{ascending:!1})]);if(N.error)throw N.error;if(_.error)throw _.error;const B=C=>({...C,type:C.report_type==="inspector_valuation"?"valuation":C.report_type==="insurance_claim"?"insurance":"standard"}),oe=(N.data??[]).map(C=>B(C)),ce=(_.data??[]).map(C=>
81C.report).filter(Boolean).map(C=>B(C)),de=[...oe,...ce],te=new Set,re=de.filter(C=>te.has(C.id)?!1:(te.add(C.id),!0));if(m(re),z){const C=re.find(n=>n.id===z);C&&o(C)}}catch(N){O(N instanceof Error?N.message:"Failed to load reports")}t(!1)}j()},[a,z]);const R=j=>{o(j),l({view:j.id})},P=()=>{o(null),l({})},q=()=>{g(!0),l({action:"builder"})},ee=()=>{g(!1),l({})};return u?.pdf_url?r.jsxs("div",{className:"p-4 lg:p-6 max-w-5xl",children:[r.jsxs("nav",{className:"flex items-center gap-2 text-xs text-[var(--text3)] mb-4",children:[r.jsx(me,{to:"/owner/dashboard",className:"hover:text-[var(--text2)]",children:e("nav.dashboard")}),r.jsx(K,{size:12}),r.jsx("button",{onClick:P,className:"hover:text-[var(--text2)]",children:e("nav.reports")}),r.jsx(K,{size:12}),r.jsx("span",{className:"text-[var(--text)] truncate",children:u.title})]}),r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsx("h1",{className:"text-xl font-sans font-bold text-[var(--text)]",children:u.title}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("button",{onClick:()=>H(u),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-[var(--text3)] hover:text-[var(--text)] border border-[var(--border)] hover:border-[var(--text3)] transition-colors",children:[r.jsx(pe,{size:12}),e("reports.share.title")]}),r.jsx("button",{onClick:P,className:"p-2 rounded-lg text-[var(--text3)] hover:text-[var(--text)] hover:bg-[var(--bg3)] transition-colors",children:r.jsx(Te,{size:16})})]})]}),r.jsx(Ee,{pdfUrl:u.pdf_url,title:u.title}),h&&r.jsx(we,{report:h,onClose:()=>H(null)})]}):x?r.jsxs("div",{className:"p-4 lg:p-6 max-w-5xl",children:[r.jsxs("nav",{className:"flex items-center gap-2 text-xs text-[var(--text3)] mb-6",children:[r.jsx(me,{to:"/owner/dashboard",className:"hover:text-[var(--text2)]",children:e("nav.dashboard")}),r.jsx(K,{size:12}),r.jsx("button",{onClick:ee,className:"hover:text-[var(--text2)]",children:e("nav.reports")}),r.jsx(K,{size:12}),r.jsx("span",{className:"text-[var(--text)]",children:e("reports.builder.title")})]}),r.jsx("h1",{className:"text-xl font-sans font-bold text-[var(--text)] mb-6",children:e("reports.builder.title")}),r.jsx(ct,{onClose:ee})]}):r.jsxs("div",{className:"p-4 lg:p-6 max-w-5xl",children:[r.jsxs("nav",{className:"flex items-center gap-2 text-xs text-[var(--text3)] mb-6",children:[r.jsx(me,{to:"/owner/dashboard",className:"hover:text-[var(--text2)]",children:e("nav.dashboard")}),r.jsx(K,{size:12}),r.jsx("span",{className:"text-[var(--text)]",children:e("nav.reports")})]}),r.jsxs("div",{className:"flex items-center justify-between mb-6",children:[r.jsx("h1",{className:"text-xl font-sans font-bold text-[var(--text)]",children:e("nav.reports")}),r.jsxs("button",{onClick:q,className:"flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold bg-[var(--green)] text-[var(--bg)] hover:brightness-110 transition",children:[r.jsx(Ge,{size:16}),e("reports.builder.title")]})]}),S&&r.jsx("div",{className:"mb-4",children:r.jsx(Ke,{message:S,onRetry:()=>window.location.reload()})}),r.jsxs("div",{className:"mb-8",children:[r.jsx("h2",{className:"text-xs font-semibold text-[var(--text2)] uppercase tracking-wider mb-3",children:e("reports.quick.title")}),r.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:dt.map(j=>{const N=j.icon;return r.jsxs("button",{onClick:q,className:"flex flex-col items-center gap-2 p-4 rounded-xl border border-[var(--border)] bg-[var(--bg2)] hover:bg-[var(--bg3)] transition-all text-center",children:[r.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center",style:{background:`${j.color}15`,color:j.color},children:r.jsx(N,{size:18})}),r.jsx("span",{className:"text-xs font-medium text-[var(--text)]",children:e(j.labelKey)})]},j.id)})})]}),r.jsxs("div",{children:[r.jsx("h2",{className:"text-xs font-semibold text-[var(--text2)] uppercase tracking-wider mb-3",children:e("reports.history.title")}),s?r.jsx("div",{className:"flex items-center justify-center py-12",children:r.jsx(Me,{size:24,className:"animate-spin text-[var(--green)]"})}):c.length===0?r.jsxs("div",{className:"rounded-xl border border-[var(--border)] bg-[var(--bg2)] p-8 text-center",children:[r.jsx(Ue,{size:24,className:"mx-auto text-[var(--text3)] mb-2"}),r.jsx("p",{className:"text-sm text-[var(--text2)]",children:e("reports.history.empty")}),r.jsx("button",{onClick:q,className:"inline-block mt-3 px-4 py-2 rounded-lg text-xs font-semibold bg-[var(--green)] text-[var(--bg)] hover:brightness-110 transition",children:e("reports.builder.title")})]}):r.jsx("div",{className:"space-y-3",children:c.map(j=>r.jsxs("div",{className:"relative group",children:[r.jsx(Re,{report:j,onClick:R}),r.jsx("button",{onClick:N=>{N.stopPropagation(),H(j)},className:"absolute top-3 right-3 p-1.5 rounded-lg opacity-0 group-hover:opacity-100 text-[var(--text3)] hover:text-[var(--text)] hover:bg-[var(--bg3)] transition-all",title:e("reports.share.title"),children:r.jsx(pe,{size:12})})]},j.id))})]}),h&&r.jsx(we,{report:h,onClose:()=>H(null)})]})}export{Bt as default}; 82//# sourceMappingURL=ReportsPage-J4HMsy44.js.map
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.