import{j as e,m as L,A as Ce}from"./vendor-animation-0s3FMHwK.js";import{r as o,h as ze,g as De,L as ye}from"./vendor-react-BVs3cwbi.js";import{g as te,c as A,a as Pe,u as Ae,b as Te,F,A as ve,C as ge}from"./index-Bay45BGf.js";import{F as $e}from"./Forbidden-D25jV3Oq.js";import{u as Oe,a as fe,b as Ie,D as Fe,r as Me,c as Be,S as Ee,v as Re,d as Le,e as Ze,K as We,T as Ve,P as He}from"./useSortableList-CgbuKaxB.js";import{a9 as Ke}from"./vendor-utils-Dyr8OjFr.js";import qe from"./RichEditor-Bfur5pi6.js";function Ue({items:j,setItems:c,updateItem:u,addItem:b,removeItem:z,itemTemplates:C,showItemTemplateMenu:T,setShowItemTemplateMenu:_,addItemFromTemplate:$,totals:i,currency:v,applyVat:k,vatRate:x,itemsError:l,readOnly:y}){const Z=Oe(fe(He,{activationConstraint:{distance:5}}),fe(Ve,{activationConstraint:{delay:200,tolerance:5}}),fe(We)),{handleDragEnd:p}=Ie(c,"_key");return e.jsxs(L.div,{className:"offers-editor-section",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.4,delay:.2},children:[e.jsxs("div",{className:"flex-between mb-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"admin-card-title",style:{margin:0},children:"Položky"}),l&&e.jsx("span",{className:"admin-form-error",children:l})]}),!y&&e.jsxs("div",{style:{display:"flex",gap:"0.5rem",position:"relative"},children:[C.length>0&&e.jsxs("div",{style:{position:"relative"},children:[e.jsx("button",{type:"button",onClick:()=>_(d=>!d),className:"admin-btn admin-btn-secondary admin-btn-sm",children:"Ze šablony"}),T&&e.jsx("div",{className:"offers-template-menu",children:C.map(d=>e.jsxs("div",{className:"offers-template-menu-item",onClick:()=>$(d),children:[e.jsx("div",{className:"fw-500",children:d.name}),d.default_price>0&&e.jsx("div",{style:{fontSize:"0.75rem",color:"var(--text-tertiary)"},children:Number(d.default_price).toFixed(2)})]},d.id))})]}),e.jsx("button",{type:"button",onClick:b,className:"admin-btn admin-btn-primary admin-btn-sm",children:"+ Přidat položku"})]})]}),e.jsx("div",{className:"offers-items-table",children:e.jsxs("table",{className:"admin-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[!y&&e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{style:{width:"2.5rem",textAlign:"center"},children:"#"}),e.jsx("th",{children:"Popis položky"}),e.jsx("th",{style:{width:"5.5rem",textAlign:"center"},children:"Množství"}),e.jsx("th",{style:{width:"5.5rem",textAlign:"center"},children:"Jednotka"}),e.jsx("th",{style:{width:"5.5rem",textAlign:"center"},children:"Jedn. cena"}),e.jsx("th",{style:{width:"4.5rem",textAlign:"center"},children:"V ceně"}),e.jsx("th",{style:{width:"8rem",textAlign:"right"},children:"Celkem"}),!y&&e.jsx("th",{style:{width:"2.5rem",textAlign:"center"}})]})}),e.jsx(Fe,{sensors:Z,collisionDetection:Be,onDragEnd:p,modifiers:[Me],children:e.jsx(Ee,{items:j.map(d=>String(d._key)),strategy:Re,children:e.jsx("tbody",{children:j.map((d,g)=>{const D=(Number(d.quantity)||0)*(Number(d.unit_price)||0);return e.jsx(Le,{id:String(d._key),disabled:y,children:({attributes:I,listeners:P})=>e.jsxs(e.Fragment,{children:[!y&&e.jsx("td",{style:{width:"2rem"},children:e.jsx(Ze,{listeners:P,attributes:I})}),e.jsx("td",{style:{color:"var(--text-tertiary)",textAlign:"center",fontWeight:500},children:g+1}),e.jsxs("td",{children:[e.jsx("input",{type:"text",value:d.description,onChange:w=>u(g,"description",w.target.value),className:"admin-form-input",placeholder:"Název položky",style:{marginBottom:"0.5rem",fontWeight:500},readOnly:y}),e.jsx("input",{type:"text",value:d.item_description,onChange:w=>u(g,"item_description",w.target.value),className:"admin-form-input",placeholder:"Podrobný popis (volitelný)",style:{fontSize:"0.8rem",opacity:.8},readOnly:y})]}),e.jsx("td",{children:e.jsx("input",{type:"number",value:d.quantity,onChange:w=>u(g,"quantity",parseFloat(w.target.value)||0),className:"admin-form-input",min:"0",step:"1",style:{textAlign:"center",height:"2.25rem",padding:"0.375rem 0.5rem"},readOnly:y})}),e.jsx("td",{children:e.jsx("input",{type:"text",value:d.unit,onChange:w=>u(g,"unit",w.target.value),className:"admin-form-input",placeholder:"hod",style:{textAlign:"center",height:"2.25rem",padding:"0.375rem 0.5rem"},readOnly:y})}),e.jsx("td",{children:e.jsx("input",{type:"number",value:d.unit_price,onChange:w=>u(g,"unit_price",parseFloat(w.target.value)||0),className:"admin-form-input",min:"0",step:"0.01",style:{textAlign:"right",height:"2.25rem",padding:"0.375rem 0.5rem"},readOnly:y})}),e.jsx("td",{style:{textAlign:"center"},children:e.jsxs("label",{className:"admin-form-checkbox",style:{justifyContent:"center"},children:[e.jsx("input",{type:"checkbox",checked:d.is_included_in_total,onChange:w=>u(g,"is_included_in_total",w.target.checked),disabled:y}),e.jsx("span",{})]})}),e.jsx("td",{style:{textAlign:"right",fontWeight:600,whiteSpace:"nowrap",fontSize:"0.875rem"},children:te(D,v)}),!y&&e.jsx("td",{children:j.length>1&&e.jsx("button",{type:"button",onClick:()=>z(g),className:"admin-btn-icon danger",title:"Odebrat","aria-label":"Odebrat",children:e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})})]})},d._key)})})})})]})}),e.jsxs("div",{className:"offers-totals-summary",children:[e.jsxs("div",{className:"offers-totals-row",children:[e.jsx("span",{children:"Mezisoučet:"}),e.jsx("span",{children:te(i.subtotal,v)})]}),k&&e.jsxs("div",{className:"offers-totals-row",children:[e.jsxs("span",{children:["DPH (",x,"%):"]}),e.jsx("span",{children:te(i.vatAmount,v)})]}),e.jsxs("div",{className:"offers-totals-row offers-totals-total",children:[e.jsx("span",{children:"Celkem k úhradě:"}),e.jsx("span",{children:te(i.total,v)})]})]})]})}function Je({sections:j,addSection:c,removeSection:u,updateSection:b,moveSection:z,scopeTemplates:C,showScopeTemplateMenu:T,setShowScopeTemplateMenu:_,loadScopeTemplate:$,form:i,updateForm:v,readOnly:k}){return e.jsxs(L.div,{className:"offers-editor-section",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.4,delay:.3},children:[e.jsxs("div",{className:"flex-between mb-4",children:[e.jsx("h3",{className:"admin-card-title",style:{margin:0},children:"Rozsah projektu"}),!k&&e.jsxs("div",{style:{display:"flex",gap:"0.5rem",position:"relative"},children:[C.length>0&&e.jsxs("div",{style:{position:"relative"},children:[e.jsx("button",{type:"button",onClick:()=>_(x=>!x),className:"admin-btn admin-btn-secondary admin-btn-sm",children:"Ze šablony"}),T&&e.jsx("div",{className:"offers-template-menu",children:C.map(x=>e.jsx("div",{className:"offers-template-menu-item",onClick:()=>$(x),children:x.name},x.id))})]}),e.jsx("button",{type:"button",onClick:c,className:"admin-btn admin-btn-primary admin-btn-sm",children:"+ Přidat sekci"})]})]}),e.jsx("div",{className:"admin-form",children:e.jsxs("div",{className:"admin-form-row",children:[e.jsxs("div",{className:"admin-form-group",children:[e.jsx("label",{className:"admin-form-label",children:"Název rozsahu"}),e.jsx("input",{type:"text",value:i.scope_title,onChange:x=>v("scope_title",x.target.value),className:"admin-form-input",placeholder:"Rozsah projektu",readOnly:k})]}),e.jsxs("div",{className:"admin-form-group",children:[e.jsx("label",{className:"admin-form-label",children:"Popis rozsahu"}),e.jsx("input",{type:"text",value:i.scope_description,onChange:x=>v("scope_description",x.target.value),className:"admin-form-input",placeholder:"Volitelný popis",readOnly:k})]})]})}),j.length===0?e.jsx("div",{className:"admin-empty-state",style:{padding:"2rem"},children:e.jsx("p",{style:{color:"var(--text-tertiary)"},children:'Žádné sekce rozsahu. Klikněte na "Přidat sekci" pro přidání.'})}):e.jsx("div",{className:"offers-scope-list",children:j.map((x,l)=>e.jsxs("div",{className:"offers-scope-section",children:[e.jsxs("div",{className:"offers-scope-section-header",children:[e.jsxs("span",{className:"offers-scope-number",children:[l+1,"."]}),e.jsx("span",{className:"offers-scope-title",children:i.language==="CZ"&&x.title_cz||x.title||`Sekce ${l+1}`}),!k&&e.jsxs("div",{className:"offers-scope-actions",children:[e.jsx("button",{type:"button",onClick:()=>z(l,-1),disabled:l===0,className:"admin-btn-icon",title:"Nahoru","aria-label":"Nahoru",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M18 15l-6-6-6 6"})})}),e.jsx("button",{type:"button",onClick:()=>z(l,1),disabled:l===j.length-1,className:"admin-btn-icon",title:"Dolů","aria-label":"Dolů",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M6 9l6 6 6-6"})})}),e.jsx("button",{type:"button",onClick:()=>u(l),className:"admin-btn-icon danger",title:"Odebrat","aria-label":"Odebrat",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),e.jsxs("div",{className:"admin-form",children:[e.jsxs("div",{className:"admin-form-row",children:[e.jsxs("div",{className:"admin-form-group",children:[e.jsxs("label",{className:"admin-form-label",children:[e.jsx("span",{className:"offers-lang-badge",children:"EN"}),"Název sekce"]}),e.jsx("input",{type:"text",value:x.title,onChange:y=>b(l,"title",y.target.value),className:"admin-form-input",placeholder:"Název sekce (anglicky)",readOnly:k})]}),e.jsxs("div",{className:"admin-form-group",children:[e.jsxs("label",{className:"admin-form-label",children:[e.jsx("span",{className:"offers-lang-badge offers-lang-badge-cz",children:"CZ"}),"Název sekce"]}),e.jsx("input",{type:"text",value:x.title_cz,onChange:y=>b(l,"title_cz",y.target.value),className:"admin-form-input",placeholder:"Název sekce (česky)",readOnly:k})]})]}),e.jsxs("div",{className:"admin-form-group",children:[e.jsx("label",{className:"admin-form-label",children:"Obsah"}),k?x.content&&e.jsx("div",{className:"offers-scope-content rich-text-view",style:{padding:"1rem"},dangerouslySetInnerHTML:{__html:Ke.sanitize(x.content)}}):e.jsx(qe,{value:x.content,onChange:y=>b(l,"content",y),placeholder:"Obsah sekce...",minHeight:"150px"})]})]})]},x._key||l))})]})}function Ge({customers:j,customerId:c,customerName:u,onSelect:b,onClear:z,error:C,readOnly:T}){const[_,$]=o.useState(""),[i,v]=o.useState(!1);o.useEffect(()=>{const l=()=>v(!1);if(i)return document.addEventListener("click",l),()=>document.removeEventListener("click",l)},[i]);const k=o.useMemo(()=>{if(!_)return j;const l=_.toLowerCase();return j.filter(y=>(y.name||"").toLowerCase().includes(l)||(y.company_id||"").includes(_)||(y.city||"").toLowerCase().includes(l))},[j,_]),x=l=>{b(l),$(""),v(!1)};return e.jsxs("div",{className:`admin-form-group${C?" has-error":""}`,children:[e.jsx("label",{className:"admin-form-label required",children:"Zákazník"}),c&&e.jsxs("div",{className:"offers-customer-selected",children:[e.jsx("span",{children:u}),!T&&e.jsx("button",{type:"button",onClick:z,className:"admin-btn-icon",title:"Odebrat zákazníka","aria-label":"Odebrat zákazníka",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),!c&&!T&&e.jsxs("div",{className:"offers-customer-select",onClick:l=>l.stopPropagation(),children:[e.jsx("input",{type:"text",value:_,onChange:l=>{$(l.target.value),v(!0)},onFocus:()=>v(!0),className:"admin-form-input",placeholder:"Hledat zákazníka..."}),i&&e.jsx("div",{className:"offers-customer-dropdown",children:k.length===0?e.jsx("div",{className:"offers-customer-dropdown-empty",children:"Žádní zákazníci"}):k.slice(0,10).map(l=>e.jsxs("div",{className:"offers-customer-dropdown-item",onMouseDown:()=>x(l),children:[e.jsx("div",{children:l.name}),l.city&&e.jsx("div",{children:l.city})]},l.id))})]}),C&&e.jsx("span",{className:"admin-form-error",children:C})]})}const M="/api/admin";let B=0;const be=()=>({_key:`item-${++B}`,description:"",item_description:"",quantity:1,unit:"",unit_price:0,is_included_in_total:!0}),Ye=()=>({_key:`sec-${++B}`,title:"",title_cz:"",content:""});function Qe(j){return j.map(c=>({...c,_key:c._key||`item-${++B}`}))}function Xe(j){return j.map(c=>({...c,_key:c._key||`sec-${++B}`}))}const q="boha_offer_draft",et={quotation_number:"",project_code:"",customer_id:null,customer_name:"",created_at:new Date().toISOString().split("T")[0],valid_until:new Date(Date.now()+30*24*60*60*1e3).toISOString().split("T")[0],currency:"EUR",language:"EN",vat_rate:21,apply_vat:!1,exchange_rate:"",exchange_rate_date:"",scope_title:"",scope_description:""};function tt({id:j,isEdit:c,alert:u,navigate:b}){const[z,C]=o.useState(c),[T,_]=o.useState(!1),[$,i]=o.useState({}),[v,k]=o.useState([]),[x,l]=o.useState([]),[y,Z]=o.useState([]),[p,d]=o.useState({...et}),[g,D]=o.useState([be()]),[I,P]=o.useState([]),[w,se]=o.useState(null),[ne,U]=o.useState("active"),[W,V]=o.useState(null),J=o.useRef({form:p,items:g,sections:I}),G=o.useRef(!1);o.useEffect(()=>{(async()=>{try{const[a,s,m]=await Promise.all([A(`${M}/customers.php`),A(`${M}/offers-templates.php?action=items`),A(`${M}/offers-templates.php?action=scopes`)]),n=await a.json(),h=await s.json(),f=await m.json();n.success&&k(n.data.customers),h.success&&l(h.data.templates),f.success&&Z(f.data.templates)}catch{}})()},[]),o.useEffect(()=>{if(!c)try{const t=localStorage.getItem(q);if(!t)return;const a=JSON.parse(t);if(!a||typeof a!="object"||!a.form||!Array.isArray(a.items)){localStorage.removeItem(q);return}const{form:s,items:m,sections:n,savedAt:h}=a;d(f=>({...f,project_code:s.project_code??f.project_code,customer_id:s.customer_id??f.customer_id,customer_name:s.customer_name??f.customer_name,created_at:s.created_at??f.created_at,valid_until:s.valid_until??f.valid_until,currency:s.currency??f.currency,language:s.language??f.language,vat_rate:s.vat_rate??f.vat_rate,apply_vat:s.apply_vat??f.apply_vat,exchange_rate:s.exchange_rate??f.exchange_rate,exchange_rate_date:s.exchange_rate_date??f.exchange_rate_date,scope_title:s.scope_title??f.scope_title,scope_description:s.scope_description??f.scope_description})),m.length&&D(Qe(m)),Array.isArray(n)&&n.length&&P(Xe(n)),G.current=!0,h&&V(new Date(h))}catch{try{localStorage.removeItem(q)}catch{}}},[c]),o.useEffect(()=>{J.current={form:p,items:g,sections:I}},[p,g,I]),o.useEffect(()=>{if(c)return;const t=setTimeout(()=>{try{const{form:a,items:s,sections:m}=J.current,{quotation_number:n,...h}=a,f=new Date().toISOString();localStorage.setItem(q,JSON.stringify({form:h,items:s,sections:m,savedAt:f})),V(new Date(f))}catch{}},500);return()=>clearTimeout(t)},[p,g,I,c]),o.useEffect(()=>{if(!c){const a=async()=>{try{const n=await(await A(`${M}/offers.php?action=next_number`)).json();n.success&&d(h=>({...h,quotation_number:n.data.number}))}catch{}},s=async()=>{try{const n=await(await A(`${M}/company-settings.php`)).json();if(n.success&&!G.current){const h=n.data;d(f=>({...f,currency:h.default_currency||f.currency,vat_rate:h.default_vat_rate||f.vat_rate}))}}catch{}};a(),s();return}(async()=>{try{const a=await A(`${M}/offers.php?action=detail&id=${j}`);if(a.status===401)return;const s=await a.json();s.success?ie(s.data):(u.error(s.error||"Nepodařilo se načíst nabídku"),b("/offers"))}catch{u.error("Chyba připojení"),b("/offers")}finally{C(!1)}})()},[c,j,u,b]);const ie=t=>{d({quotation_number:t.quotation_number||"",project_code:t.project_code||"",customer_id:t.customer_id||null,customer_name:t.customer_name||"",created_at:(t.created_at||"").substring(0,10),valid_until:(t.valid_until||"").substring(0,10),currency:t.currency||"EUR",language:t.language||"EN",vat_rate:t.vat_rate||21,apply_vat:!!t.apply_vat,exchange_rate:t.exchange_rate||"",exchange_rate_date:t.exchange_rate_date||"",scope_title:t.scope_title||"",scope_description:t.scope_description||""}),t.items?.length&&D(t.items.map(a=>({_key:`item-${++B}`,description:a.description||"",item_description:a.item_description||"",quantity:Number(a.quantity)||1,unit:a.unit||"",unit_price:Number(a.unit_price)||0,is_included_in_total:!!a.is_included_in_total}))),t.sections?.length&&(D(a=>a),P(t.sections.map(a=>({_key:`sec-${++B}`,title:a.title||"",title_cz:a.title_cz||"",content:a.content||""})))),se(t.order||null),U(t.status||"active")},re=o.useMemo(()=>{const t=g.reduce((s,m)=>m.is_included_in_total?s+(Number(m.quantity)||0)*(Number(m.unit_price)||0):s,0),a=p.apply_vat?t*((Number(p.vat_rate)||0)/100):0;return{subtotal:t,vatAmount:a,total:t+a}},[g,p.apply_vat,p.vat_rate]),Y=o.useCallback(()=>{try{localStorage.removeItem(q)}catch{}V(null)},[]),oe=o.useMemo(()=>W?W.toLocaleTimeString("cs-CZ",{hour:"2-digit",minute:"2-digit"}):null,[W]),le=(t,a)=>d(s=>({...s,[t]:a})),ce=t=>{d(a=>({...a,customer_id:t.id,customer_name:t.name})),i(a=>({...a,customer_id:void 0}))},de=()=>{d(t=>({...t,customer_id:null,customer_name:""}))},me=(t,a,s)=>{D(m=>m.map((n,h)=>h===t?{...n,[a]:s}:n))},ue=()=>D(t=>[...t,be()]),H=t=>{D(a=>a.length>1?a.filter((s,m)=>m!==t):a)},pe=t=>{D(a=>[...a,{_key:`item-${++B}`,description:t.name||"",item_description:t.description||"",quantity:1,unit:"",unit_price:Number(t.default_price)||0,is_included_in_total:!0}])},Q=()=>P(t=>[...t,Ye()]),E=t=>{P(a=>a.filter((s,m)=>m!==t))},X=(t,a,s)=>{P(m=>m.map((n,h)=>h===t?{...n,[a]:s}:n))},ee=(t,a)=>{P(s=>{const m=[...s],n=t+a;return n<0||n>=m.length?s:([m[t],m[n]]=[m[n],m[t]],m)})},R=async t=>{try{const s=await(await A(`${M}/offers-templates.php?action=scope_detail&id=${t.id}`)).json();if(s.success){const m=s.data;if(d(n=>({...n,scope_description:m.description||n.scope_description})),m.sections){const n=m.sections.map(h=>({_key:`sec-${++B}`,title:h.title||"",title_cz:h.title_cz||"",content:h.content||""}));P(h=>[...h,...n])}u.success(`Načtena šablona "${t.name}"`)}}catch{u.error("Nepodařilo se načíst šablonu")}},he=async()=>{const t={};if(p.customer_id||(t.customer_id="Vyberte zákazníka"),p.created_at||(t.created_at="Zadejte datum"),p.valid_until||(t.valid_until="Zadejte datum"),(g.length===0||g.every(a=>!a.description.trim()))&&(t.items="Přidejte alespoň jednu položku"),i(t),!(Object.keys(t).length>0)){_(!0);try{const a=K(),s=c?`${M}/offers.php?id=${j}`:`${M}/offers.php`,n=await(await A(s,{method:c?"PUT":"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})).json();if(n.success){if(u.success(n.message||(c?"Nabídka byla uložena":"Nabídka byla vytvořena")),!c&&n.data?.id){Y();const h=n.data.id;setTimeout(()=>b(`/offers/${h}`,{replace:!0}),300)}}else u.error(n.error||"Nepodařilo se uložit nabídku")}catch{u.error("Chyba připojení")}finally{_(!1)}}},K=()=>({quotation:{project_code:p.project_code,customer_id:p.customer_id,created_at:p.created_at,valid_until:p.valid_until,currency:p.currency,language:p.language,vat_rate:p.vat_rate,apply_vat:p.apply_vat,exchange_rate:p.exchange_rate||null,exchange_rate_date:p.exchange_rate_date||null,scope_title:p.scope_title,scope_description:p.scope_description},items:g.map((t,a)=>({...t,position:a+1})),sections:I.map((t,a)=>({...t,position:a+1}))});return{loading:z,saving:T,errors:$,setErrors:i,form:p,updateForm:le,items:g,setItems:D,sections:I,customers:v,itemTemplates:x,scopeTemplates:y,orderInfo:w,offerStatus:ne,setOfferStatus:U,totals:re,draftSavedAtLabel:oe,clearDraft:Y,selectCustomer:ce,clearCustomer:de,updateItem:me,addItem:ue,removeItem:H,addItemFromTemplate:pe,addSection:Q,removeSection:E,updateSection:X,moveSection:ee,loadScopeTemplate:R,handleSave:he}}const ae="/api/admin";function dt(){const{id:j}=ze(),c=!!j,u=Pe(),{hasPermission:b}=Ae(),z=De(),{loading:C,saving:T,errors:_,setErrors:$,form:i,updateForm:v,items:k,setItems:x,sections:l,customers:y,itemTemplates:Z,scopeTemplates:p,orderInfo:d,offerStatus:g,setOfferStatus:D,totals:I,draftSavedAtLabel:P,selectCustomer:w,clearCustomer:se,updateItem:ne,addItem:U,removeItem:W,addItemFromTemplate:V,addSection:J,removeSection:G,updateSection:ie,moveSection:re,loadScopeTemplate:Y,handleSave:oe}=tt({id:j,isEdit:c,alert:u,navigate:z}),[le,ce]=o.useState(!1),[de,me]=o.useState(!1),[ue,H]=o.useState(!1),[pe,Q]=o.useState(!1),[E,X]=o.useState(!1),[ee,R]=o.useState(!1),[he,K]=o.useState(!1),[t,a]=o.useState(!1),[s,m]=o.useState(""),[n,h]=o.useState(null),[f,xe]=o.useState(!1);Te(ee);const N=g==="invalidated",_e=c&&!N&&!d&&i.valid_until&&new Date(i.valid_until){if(!s.trim()){u.error("Číslo objednávky zákazníka je povinné");return}X(!0);try{const r=new FormData;r.append("quotationId",j),r.append("customerOrderNumber",s.trim()),n&&r.append("attachment",n);const O=await(await A(`${ae}/orders.php`,{method:"POST",body:r})).json();O.success?(R(!1),u.success(O.message||"Objednávka byla vytvořena"),z(`/orders/${O.data.order_id}`)):u.error(O.error||"Nepodařilo se vytvořit objednávku")}catch{u.error("Chyba připojení")}finally{X(!1)}},Ne=async()=>{a(!0);try{const S=await(await A(`${ae}/offers.php?action=invalidate&id=${j}`,{method:"POST"})).json();S.success?(K(!1),D("invalidated"),u.success(S.message||"Nabídka byla zneplatněna")):u.error(S.error||"Nepodařilo se zneplatnit nabídku")}catch{u.error("Chyba připojení")}finally{a(!1)}},ke=async()=>{Q(!0);try{const S=await(await A(`${ae}/offers.php?id=${j}`,{method:"DELETE"})).json();S.success?(u.success(S.message||"Nabídka byla smazána"),z("/offers")):u.error(S.error||"Nepodařilo se smazat nabídku")}catch{u.error("Chyba připojení")}finally{Q(!1),H(!1)}},we=async()=>{if(!(!c||f)){xe(!0);try{const r=await A(`${ae}/offers-pdf.php?id=${j}`);if(r.status===401)return;if(!r.ok){u.error("Nepodařilo se vygenerovat PDF");return}const S=await r.text(),O=window.open("","_blank");O?(O.document.open(),O.document.write(S),O.document.close(),O.onload=()=>O.print()):u.error("Prohlížeč zablokoval vyskakovací okno")}catch{u.error("Chyba při generování PDF")}finally{xe(!1)}}},Se=c?N?"offers.view":"offers.edit":"offers.create";return b(Se)?C?e.jsxs("div",{className:"admin-skeleton",style:{padding:0,gap:"1.5rem"},children:[e.jsxs("div",{className:"admin-skeleton-row",style:{justifyContent:"space-between"},children:[e.jsxs("div",{className:"flex-row-gap",children:[e.jsx("div",{className:"admin-skeleton-line",style:{width:"32px",height:"32px",borderRadius:"8px"}}),e.jsx("div",{className:"admin-skeleton-line h-8",style:{width:"200px"}})]}),e.jsxs("div",{className:"admin-skeleton-row gap-2",children:[e.jsx("div",{className:"admin-skeleton-line h-10",style:{width:"100px",borderRadius:"8px"}}),e.jsx("div",{className:"admin-skeleton-line h-10",style:{width:"100px",borderRadius:"8px"}})]})]}),e.jsx("div",{className:"admin-card",children:e.jsx("div",{className:"admin-skeleton",style:{gap:"1.25rem"},children:[0,1,2,3].map(r=>e.jsxs("div",{className:"admin-skeleton-row",children:[e.jsx("div",{className:"admin-skeleton-line w-1/4"}),e.jsx("div",{className:"admin-skeleton-line w-1/2"})]},r))})}),e.jsx("div",{className:"admin-card",children:e.jsx("div",{className:"admin-skeleton",style:{gap:"1.25rem"},children:[0,1,2].map(r=>e.jsxs("div",{className:"admin-skeleton-row",children:[e.jsx("div",{className:"flex-1",children:e.jsx("div",{className:"admin-skeleton-line w-full"})}),e.jsx("div",{className:"flex-1",children:e.jsx("div",{className:"admin-skeleton-line w-3/4"})}),e.jsx("div",{className:"flex-1",children:e.jsx("div",{className:"admin-skeleton-line w-1/2"})})]},r))})}),e.jsx("div",{className:"admin-card",children:e.jsx("div",{className:"admin-skeleton",style:{gap:"1.25rem"},children:[0,1,2].map(r=>e.jsxs("div",{className:"admin-skeleton-row",children:[e.jsx("div",{className:"admin-skeleton-line w-1/3"}),e.jsx("div",{className:"admin-skeleton-line w-full"})]},r))})})]}):e.jsxs("div",{children:[e.jsxs(L.div,{className:"admin-page-header",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.4},children:[e.jsxs("div",{className:"flex-row gap-4",children:[e.jsx(ye,{to:"/offers",className:"admin-btn-icon",title:"Zpět","aria-label":"Zpět",children:e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M19 12H5M12 19l-7-7 7-7"})})}),e.jsxs("div",{children:[e.jsxs("h1",{className:"admin-page-title",children:[c?`Nabídka ${i.quotation_number}`:"Nová nabídka",N&&e.jsx("span",{className:"admin-badge admin-badge-danger",style:{marginLeft:"0.75rem",verticalAlign:"middle",fontSize:"0.75rem"},children:"Zneplatněna"})]}),!c&&P&&e.jsxs("div",{className:"offers-draft-indicator",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})}),"Koncept uložen ",P]})]})]}),e.jsxs("div",{className:"admin-page-actions",children:[c&&b("offers.export")&&e.jsx("button",{onClick:we,className:"admin-btn admin-btn-secondary",disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"admin-spinner admin-spinner-sm"}),"PDF..."]}):e.jsxs(e.Fragment,{children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.jsx("polyline",{points:"14 2 14 8 20 8"})]}),"PDF"]})}),c&&!N&&b("orders.create")&&!d&&e.jsxs("button",{onClick:()=>{m(""),h(null),R(!0)},className:"admin-btn admin-btn-secondary",children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.jsx("polyline",{points:"14 2 14 8 20 8"}),e.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),e.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]}),"Vytvořit objednávku"]}),c&&d&&e.jsxs(ye,{to:`/orders/${d.id}`,className:"admin-btn admin-btn-secondary",children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.jsx("polyline",{points:"14 2 14 8 20 8"})]}),"Objednávka ",d.order_number]}),_e&&b("offers.edit")&&e.jsxs("button",{onClick:()=>K(!0),className:"admin-btn admin-btn-secondary",children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("line",{x1:"4.93",y1:"4.93",x2:"19.07",y2:"19.07"})]}),"Zneplatnit"]}),!N&&e.jsx("button",{onClick:oe,className:"admin-btn admin-btn-primary",disabled:T,children:T?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"admin-spinner admin-spinner-sm"}),"Ukládání..."]}):"Uložit"}),c&&b("offers.delete")&&e.jsx("button",{onClick:()=>H(!0),className:"admin-btn admin-btn-primary",children:"Smazat"})]})]}),e.jsxs(L.div,{className:`offers-editor-section${N?" offers-readonly":""}`,initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.4,delay:.1},children:[e.jsx("h3",{className:"admin-card-title",children:"Základní údaje"}),e.jsxs("div",{className:"admin-form",children:[e.jsxs("div",{className:"offers-form-row-3",children:[e.jsx(F,{label:"Číslo nabídky",children:e.jsx("input",{type:"text",value:i.quotation_number,className:"admin-form-input",readOnly:!0,style:{backgroundColor:"var(--bg-secondary)",cursor:"default"}})}),e.jsx(F,{label:"Kód projektu",children:e.jsx("input",{type:"text",value:i.project_code,onChange:r=>v("project_code",r.target.value),className:"admin-form-input",placeholder:"Volitelný kód projektu",readOnly:N})}),e.jsx(Ge,{customers:y,customerId:i.customer_id,customerName:i.customer_name,onSelect:w,onClear:se,error:_.customer_id,readOnly:N})]}),e.jsxs("div",{className:"admin-form-row",children:[e.jsx(F,{label:"Datum vytvoření",error:_.created_at,required:!0,children:N?e.jsx("input",{type:"text",value:i.created_at,className:"admin-form-input",readOnly:!0}):e.jsx(ve,{mode:"date",value:i.created_at,onChange:r=>{v("created_at",r),$(S=>({...S,created_at:void 0}))}})}),e.jsx(F,{label:"Platnost do",error:_.valid_until,required:!0,children:N?e.jsx("input",{type:"text",value:i.valid_until,className:"admin-form-input",readOnly:!0}):e.jsx(ve,{mode:"date",value:i.valid_until,onChange:r=>{v("valid_until",r),$(S=>({...S,valid_until:void 0}))}})})]}),e.jsxs("div",{className:"admin-form-row",children:[e.jsx(F,{label:"Měna",children:e.jsxs("select",{value:i.currency,onChange:r=>v("currency",r.target.value),className:"admin-form-select",disabled:N,children:[e.jsx("option",{value:"EUR",children:"EUR (€)"}),e.jsx("option",{value:"USD",children:"USD ($)"}),e.jsx("option",{value:"CZK",children:"CZK (Kč)"}),e.jsx("option",{value:"GBP",children:"GBP (£)"})]})}),e.jsx(F,{label:"Jazyk nabídky",children:e.jsxs("select",{value:i.language,onChange:r=>v("language",r.target.value),className:"admin-form-select",disabled:N,children:[e.jsx("option",{value:"EN",children:"English"}),e.jsx("option",{value:"CZ",children:"Čeština"})]})})]}),e.jsxs("div",{className:"offers-form-row-3",children:[e.jsx(F,{label:"Sazba DPH (%)",children:e.jsxs("div",{className:"flex-row-gap",children:[e.jsx("input",{type:"number",value:i.vat_rate,onChange:r=>v("vat_rate",parseFloat(r.target.value)||0),className:"admin-form-input flex-1",step:"0.1",readOnly:N}),e.jsxs("label",{className:"admin-form-checkbox",style:{whiteSpace:"nowrap"},children:[e.jsx("input",{type:"checkbox",checked:i.apply_vat,onChange:r=>v("apply_vat",r.target.checked),disabled:N}),e.jsx("span",{children:"Účtovat DPH"})]})]})}),e.jsx(F,{label:"Směnný kurz",children:e.jsx("input",{type:"number",value:i.exchange_rate,onChange:r=>v("exchange_rate",r.target.value),className:"admin-form-input",placeholder:"Volitelný",step:"0.0001",readOnly:N})})]})]})]}),e.jsx(Ue,{items:k,setItems:x,updateItem:ne,addItem:U,removeItem:W,itemTemplates:Z,showItemTemplateMenu:le,setShowItemTemplateMenu:ce,addItemFromTemplate:V,totals:I,currency:i.currency,applyVat:i.apply_vat,vatRate:i.vat_rate,itemsError:_.items,readOnly:N}),e.jsx(Je,{sections:l,addSection:J,removeSection:G,updateSection:ie,moveSection:re,scopeTemplates:p,showScopeTemplateMenu:de,setShowScopeTemplateMenu:me,loadScopeTemplate:Y,form:i,updateForm:v,readOnly:N}),e.jsx(Ce,{children:ee&&e.jsxs(L.div,{className:"admin-modal-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.2},children:[e.jsx("div",{className:"admin-modal-backdrop",onClick:()=>!E&&R(!1)}),e.jsxs(L.div,{className:"admin-modal",initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{duration:.2},children:[e.jsx("div",{className:"admin-modal-header",children:e.jsx("h2",{className:"admin-modal-title",children:"Vytvořit objednávku"})}),e.jsx("div",{className:"admin-modal-body",children:e.jsxs("div",{className:"admin-form",children:[e.jsx(F,{label:"Číslo objednávky zákazníka",required:!0,children:e.jsx("input",{type:"text",value:s,onChange:r=>m(r.target.value),onKeyDown:r=>r.key==="Enter"&&!E&&je(),className:"admin-form-input",placeholder:"Např. PO-2026-001",autoFocus:!0})}),e.jsxs(F,{label:"Příloha (PDF)",children:[n?e.jsxs("div",{className:"flex-row gap-2",children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent-color)",strokeWidth:"2",children:[e.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),e.jsx("polyline",{points:"14 2 14 8 20 8"})]}),e.jsxs("span",{style:{fontSize:"0.875rem"},children:[n.name," ",e.jsxs("span",{className:"text-tertiary",children:["(",(n.size/1024).toFixed(0)," KB)"]})]}),e.jsx("button",{type:"button",onClick:()=>h(null),className:"admin-btn-icon",title:"Odebrat",style:{marginLeft:"auto"},children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M18 6L6 18M6 6l12 12"})})})]}):e.jsxs("label",{className:"admin-btn admin-btn-secondary admin-btn-sm",style:{cursor:"pointer",display:"inline-flex",alignItems:"center",gap:"0.4rem"},children:[e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),e.jsx("polyline",{points:"17 8 12 3 7 8"}),e.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),"Vybrat soubor",e.jsx("input",{type:"file",accept:"application/pdf",onChange:r=>h(r.target.files[0]||null),style:{display:"none"}})]}),e.jsx("small",{className:"admin-form-hint",style:{marginTop:"0.25rem"},children:"Max 10 MB"})]})]})}),e.jsxs("div",{className:"admin-modal-footer",children:[e.jsx("button",{onClick:()=>R(!1),className:"admin-btn admin-btn-secondary",disabled:E,children:"Zrušit"}),e.jsx("button",{onClick:je,className:"admin-btn admin-btn-primary",disabled:E||!s.trim(),children:E?"Vytváření...":"Vytvořit"})]})]})]})}),e.jsx(ge,{isOpen:he,onClose:()=>K(!1),onConfirm:Ne,title:"Zneplatnit nabídku",message:`Opravdu chcete zneplatnit nabídku "${i.quotation_number}"? Nabídka bude pouze pro čtení a nepůjde upravovat.`,confirmText:"Zneplatnit",cancelText:"Zrušit",type:"danger",loading:t}),e.jsx(ge,{isOpen:ue,onClose:()=>H(!1),onConfirm:ke,title:"Smazat nabídku",message:`Opravdu chcete smazat nabídku "${i.quotation_number}"? Budou smazány i všechny položky a sekce. Tato akce je nevratná.`,confirmText:"Smazat",cancelText:"Zrušit",type:"danger",loading:pe})]}):e.jsx($e,{})}export{dt as default};