PageSourceSearch

https://aimaster.me/assets/ProductionContractManager-Bxe8es-H.js

js aimaster.me collected 2026-10-02 00:05:50 UTC 68,702 bytes, 14 lines download raw bytes

1var mt=Object.defineProperty;var ut=(t,s,a)=>s in t?mt(t,s,{enumerable:!0,configurable:!0,writable:!0,value:a}):t[s]=a;var Ae=(t,s,a)=>ut(t,typeof s!="symbol"?s+"":s,a);import{p as xt,q as pe,t as fe,K as H,O as G,s as p,r as v,j as e,g as D,l as Ke,aN as pt,m as Fe,B as q,aw as ht,Q as gt,U as bt,W as yt,X as _t,Y as ft,Z as jt,_ as vt,$ as Nt,bH as wt,aS as Ue,ap as A,bW as kt,au as Ge,c as me,R as Ct,aM as St,v as It,N as Qe,A as Be,ao as qt}from"./index-dLiioUMp.js";import{u as Mt}from"./useProductionChannels-BI1YFCvV.js";import{p as z}from"./parseISO-DjS42IS9.js";import{f as E,i as Ve}from"./format-CVBQk5T9.js";import{a as Ce}from"./addMonths-JgYeMe2y.js";import{M as Pt}from"./MainLayout-DzB2BSdP.js";import{I as T}from"./input-D8NVd1ns.js";import{S as Dt,a as At,b as Et,c as Lt,d as ze}from"./select-DEsXwp3K.js";import{H as Ft}from"./HCaptcha-hJti5KZG.js";import{C as _e}from"./circle-check-big-BN5Y132b.js";import{C as Tt}from"./circle-x-BKLZ__rw.js";import{S as Ut}from"./save-Bgb3J4w-.js";import{P as Te,d as Ot,c as $t,g as Rt,a as Kt,b as Qt}from"./contractData-KcwcNzhz.js";import{S as Xe}from"./send-ZwX0RQbq.js";import{T as Bt}from"./trash-2-CVvDfz2m.js";import{a as re}from"./addWeeks-DwacHaQt.js";import{B as Se}from"./badge-SWOxTi8j.js";import{R as Vt}from"./receipt-BOqm4Vgi.js";import{F as Ie}from"./file-text-DcXqteyy.js";import{U as zt}from"./upload-DSyzBXaJ.js";import{P as We}from"./plus-Bbae-nNK.js";import{C as Wt}from"./chevron-right-CmJpZQ5S.js";import"./en-US-DguC7roY.js";import"./differenceInCalendarDays-DudmbeMs.js";import"./startOfDay-DaHQlETi.js";import"./avatar-DjtkOt3N.js";import"./dropdown-menu-DF5xzmte.js";import"./popover-4Z3N_PWN.js";import"./scroll-area-zDXHKUyb.js";import"./index-BdQq_4o_.js";import"./skeleton-BtqqbLFf.js";import"./gift-CXJTZTjb.js";import"./coins-BamybQzw.js";import"./useDirectMessages-37dSDjuq.js";import"./endOfMonth-CHlpE8px.js";import"./lightbulb-DE-PSPgs.js";import"./circle-help-BJF2hyou.js";import"./credit-card-BXjFi1Tx.js";import"./ThemeSwitcher-BQ6uKMLy.js";import"./shield-check-Dxm5ChyH.js";import"./wallet-BjFqBuLI.js";import"./message-circle-B0kEVkBX.js";import"./star-8Ded0Bxr.js";import"./trackUpgradeIntent-Bo1LXsPt.js";import"./useProductionAccess-BcCYg5eh.js";import"./useIsProductionInternal-CDhYPjXy.js";import"./graduation-cap-CvtUXBkJ.js";import"./flask-conical-BXQntVI1.js";import"./palette-DmOj5N7P.js";import"./users-Wz67jG4K.js";import"./settings-SsJOxsNy.js";import"./chevron-left-D7uQDDlB.js";import"./book-open-BR1QFR4Y.js";import"./message-square-FKbrk71S.js";import"./addDays-DH0yaflK.js";/**
2 * @license lucide-react v0.462.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 Ht=xt("MailPlus",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M19 16v6",key:"tddt3s"}],["path",{d:"M16 19h6",key:"xwg31i"}]]),qe=["production-contracts"];function Jt(){const{user:t}=pe();return fe({queryKey:qe,queryFn:async()=>{const{data:a,error:n}=await p.from("production_contracts").select("*").order("created_at",{ascending:!1});if(n)throw n;return a},enabled:!!t})}function Zt(){const t=H(),{user:s}=pe();return G({mutationFn:async a=>{const{data:n,error:i}=await p.from("production_contracts").insert({...a,created_by:s==null?void 0:s.id}).select().single();if(i)throw i;return n},onSuccess:()=>t.invalidateQueries({queryKey:qe})})}function Yt(){const t=H();return G({mutationFn:async({id:s,...a})=>{const{data:n,error:i}=await p.from("production_contracts").update(a).eq("id",s).select().single();if(i)throw i;return n},onSuccess:()=>t.invalidateQueries({queryKey:qe})})}function Gt(){const t=H();return G({mutationFn:async s=>{const{error:a}=await p.from("production_contracts").delete().eq("id",s);if(a)throw a},onSuccess:()=>t.invalidateQueries({queryKey:qe})})}function et(t){switch(t){case"full":return[{stages:[1,2,3],amount:19500,label:"Full",months:5,videos:25}];case"two":return[{stages:[1,2],amount:6500,label:"Stages 1+2",months:2,videos:5},{stages:[3],amount:13e3,label:"Stage 3",months:3,videos:20}];case"three":default:return[{stages:[1],amount:2e3,label:"Stage 1",months:1,videos:0},{stages:[2],amount:4500,label:"Stage 2",months:1,videos:5},{stages:[3],amount:13e3,label:"Stage 3",months:3,videos:20}]}}function Xt(t,s,a){const n=z(s),i=a||(t.length===1?"full":t.length===2?"two":"three"),l=et(i);let m=0,u=0;for(const b of t)if(b.paid){const y=l.find((M,S)=>S+1===b.stage);y&&(m+=y.months,u+=y.videos)}return{paid_end_date:m>0?E(Ce(n,m),"yyyy-MM-dd"):null,paid_video_count:u}}function es(t){const{user:s}=pe();return fe({queryKey:["production-invoices",t],queryFn:async()=>
6{if(!t)return[];const{data:a,error:n}=await p.from("production_invoices").select("*").eq("contract_id",t).order("stage",{ascending:!0});if(n)throw n;return a},enabled:!!s&&!!t})}function ts(){const t=H();return G({mutationFn:async({contractId:s,contractNumber:a,variant:n,paymentDates:i})=>{const l=et(n),{data:m}=await p.from("production_invoices").select("*").eq("contract_id",s).order("stage",{ascending:!0}),u=m||[],b=l.length;for(let y=0;y<Math.min(u.length,b);y++){const M=u[y],{error:S}=await p.from("production_invoices").update({invoice_number:`${a}-INV-${y+1}`,stage:y+1,amount:l[y].amount,due_date:i[y]||null}).eq("id",M.id);if(S)throw S}if(b>u.length){const y=l.slice(u.length).map((S,f)=>{const _=u.length+f;return{contract_id:s,invoice_number:`${a}-INV-${_+1}`,stage:_+1,amount:S.amount,due_date:i[_]||null}}),{error:M}=await p.from("production_invoices").insert(y);if(M)throw M}if(u.length>b){const y=u.slice(b).filter(M=>!M.paid);if(y.length>0){const{error:M}=await p.from("production_invoices").delete().in("id",y.map(S=>S.id));if(M)throw M}}},onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["production-invoices",a.contractId]})}})}function Ee(t,s,a,n){if(a==="completed")return{label:"✅ Completed",key:"completed",badgeClass:"bg-green-500/10 text-green-600 dark:text-green-400"};if(a==="cancelled")return{label:"❌ Cancelled",key:"cancelled",badgeClass:"bg-destructive/10 text-destructive"};const i=t.length,l=t.filter(u=>u.paid).length;if(i>0&&l===i)return{label:"💰 Fully Paid",key:"fully_paid",badgeClass:"bg-green-500/10 text-green-600 dark:text-green-400"};const m=new Set(t.filter(u=>u.paid).map(u=>u.stage));if(n!=="full")if(n==="two"){if(m.has(1)&&!m.has(2))return{label:"💳 Stage 1+2 Paid",key:"stage_1_2_paid",badgeClass:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"};if(!m.has(1)&&m.has(2))return{label:"💳 Stage 3 Paid",key:"stage_3_paid",badgeClass:"bg-blue-500/10 text-blue-600 dark:text-blue-400"}}else{if(m.has(1)&&m.has(2)&&!m.has(3))return{label:"💳 Stage 1+2 Paid",key:"stage_1_2_paid",badgeClass:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"};if(m.has(1)&&!m.has(2))return{label:"💳 Stage 1 Paid",key:"stage_1_paid",badgeClass:"bg-blue-500/10 text-blue-600 dark:text-blue-400"};if(!m.has(1)&&m.has(2))return{label:"💳 Stage 2 Paid",key:"stage_2_paid",badgeClass:"bg-blue-500/10 text-blue-600 dark:text-blue-400"};if(l>0&&l<i)return{label:`💳 ${l}/${i} Paid`,key:"partial_paid",badgeClass:"bg-blue-500/10 text-blue-600 dark:text-blue-400"}}return s?{label:"✍️ Signed",key:"signed",badgeClass:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}:{label:"📝 Draft",key:"draft",badgeClass:"bg-muted text-muted-foreground"}}function ss(t){const{user:s}=pe();return fe({queryKey:["production-invoices-batch",t.sort().join(",")],queryFn:async()=>{if(!t.length)return new Map;const{data:a,error:n}=await p.from("production_invoices").select("*").in("contract_id",t).order("stage",{ascending:!0});if(n)throw n;const i=new Map;for(const l of a){const m=i.get(l.contract_id)||[];m.push(l),i.set(l.contract_id,m)}return i},enabled:!!s&&t.length>0})}function as(){const t=H();return G({mutationFn:async({invoiceId:s,paid:a})=>{const{error:n}=await p.from("production_invoices").update({paid:a,paid_at:a?new Date().toISOString():null}).eq("id",s);if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["production-invoices"]}),t.invalidateQueries({queryKey:["production-invoices-batch"]}),t.invalidateQueries({queryKey:["production-channels"]})}})}function ns(t){return fe({queryKey:["production-documents",t],queryFn:async()=>{if(!t)return[];const{data:s,error:a}=await p.from("production_documents").select("*").eq("contract_id",t).order("created_at",{ascending:!1});if(a)throw a;return s||[]},enabled:!!t,refetchInterval:3e4})}function rs(t){return fe({queryKey:["production-documents-batch",t],queryFn:async()=>{if(!t.length)return new Map;const{data:s,error:a}=await p.from("production_documents").select("*").in("contract_id",t).eq("doc_type","contract").order("created_at",{ascending:!1});if(a)throw a;const n=new Map;for(const i of s||[]){const l=n.get(i.contract_id)||[];l.push(i),n.set(i.contract_id,l)}return n},enabled:t.length>0,refetchInterval:3e4})}function is(){const t=H(),{user:s}=pe();return G({mutationFn:async a=>{if(!s)throw new Error("Not authenticated");const{data:n,error:i}=await p.from("production_documents").insert({...a,created_by:s.id,status:"draft"}).select().single();if(i)throw i;return n},onSuccess:(a,n)=>{t.invalidateQueries({queryKey:["production-documents",n.contract_id]})}})}
6class tt extends Error{constructor(a,n,i){super(a);Ae(this,"code");Ae(this,"consentUrl");this.name="DocuSignError",this.code=n,this.consentUrl=i}}function He(t){const s=(t==null?void 0:t.error)||"docusign_error",a=(t==null?void 0:t.message)||(t==null?void 0:t.error)||"DocuSign request failed";return new tt(a,s,t==null?void 0:t.consent_url)}async function ue(t=!1){var i,l,m;if(t){const{data:u,error:b}=await p.auth.refreshSession();if(b||!((i=u.session)!=null&&i.access_token))throw new Error("No active session. Please sign in again.");return u.session.access_token}const{data:s}=await p.auth.getSession();if((l=s.session)!=null&&l.access_token)return s.session.access_token;const{data:a,error:n}=await p.auth.refreshSession();if(n||!((m=a.session)!=null&&m.access_token))throw new Error("No active session. Please sign in again.");return a.session.access_token}async function xe(t,s,a){const n=await fetch(`https://gwjmucrmfsktwhlwsckb.supabase.co/functions/v1/${t}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imd3am11Y3JtZnNrdHdobHdzY2tiIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjQ5OTYyMjIsImV4cCI6MjA4MDU3MjIyMn0.sPHQnmeZouVMLuW-wBgAYeTetgfip8hKuOK1AUMdDas"},body:JSON.stringify(s)}),i=await n.text();let l={};if(i)try{l=JSON.parse(i)}catch{l={message:i}}return{response:n,body:l}}function Oe(t,s){const a=`${(s==null?void 0:s.error)||""} ${(s==null?void 0:s.message)||""}`.toLowerCase();return t===401||a.includes("unauthorized")||a.includes("invalid token")}function cs(){const t=H();return G({mutationFn:async s=>{let a=await ue(),{response:n,body:i}=await xe("docusign-send",{documentId:s},a);if(Oe(n.status,i)){a=await ue(!0);const l=await xe("docusign-send",{documentId:s},a);n=l.response,i=l.body}if(!n.ok||i.error)throw He(i);return i},onSuccess:()=>{t.invalidateQueries({queryKey:["production-documents"]})}})}function ds(){const t=H();return G({mutationFn:async s=>{let a=await ue(),{response:n,body:i}=await xe("docusign-check-status",{documentId:s},a);if(Oe(n.status,i)){a=await ue(!0);const l=await xe("docusign-check-status",{documentId:s},a);n=l.response,i=l.body}if(!n.ok)throw new Error(i.error||"Failed to check status");return i},onSuccess:()=>{t.invalidateQueries({queryKey:["production-documents"]})}})}function ls(){const t=H();return G({mutationFn:async s=>{let a=await ue(),{response:n,body:i}=await xe("docusign-check-status",{documentId:s,action:"resend"},a);if(Oe(n.status,i)){a=await ue(!0);const l=await xe("docusign-check-status",{documentId:s,action:"resend"},a);n=l.response,i=l.body}if(!n.ok)throw new Error(i.error||"Failed to resend");return i},onSuccess:()=>{t.invalidateQueries({queryKey:["production-documents"]})}})}function os(){const t=H();return G({mutationFn:async({documentId:s,file:a,contractId:n})=>{const i=`${n}/${s}_manual_signed.pdf`,{error:l}=await p.storage.from("signed-documents").upload(i,a,{contentType:"application/pdf",upsert:!0});if(l)throw l;const{error:m}=await p.from("production_documents").update({signed_pdf_url:i,status:"signed",signed_at:new Date().toISOString(),updated_at:new Date().toISOString()}).eq("id",s);if(m)throw m;return i},onSuccess:()=>{t.invalidateQueries({queryKey:["production-documents"]})}})}async function st(t){const{data:s,error:a}=await p.storage.from("signed-documents").createSignedUrl(t,3600);if(a)throw a;return s.signedUrl}function Je({options:t,value:s,onChange:a,disabled:n}){const i=t.findIndex(m=>m.value===s),l=t.length;return e.jsxs("div",{className:"relative inline-flex h-10 w-full items-center rounded-2xl bg-black/[0.04] dark:bg-white/[0.06] backdrop-blur-xl p-1 ring-1 ring-black/[0.06] dark:ring-white/[0.08]",children:[e.jsx("div",{className:"absolute top-1 bottom-1 rounded-xl bg-white/90 dark:bg-white/15 shadow-md ring-1 ring-black/[0.06] dark:ring-white/10 transition-all duration-300 ease-[cubic-bezier(0.25,0.1,0.25,1)]",style:{left:`calc(${i} * ${100/l}% + 4px)`,width:`calc(${100/l}% - 8px)`}}),t.map(m=>e.jsx("button",{type:"button",disabled:n,onClick:()=>a(m.value),className:Fe("relative z-10 flex-1 text-center text-sm font-medium rounded-xl py-1.5 transition-colors duration-200",s===m.value?"text-foreground":"text-muted-foreground hover:text-foreground
6/70",n&&"opacity-50 cursor-not-allowed"),children:m.label},m.value))]})}const U="rounded-xl bg-card/60 backdrop-blur-xl border-0 ring-1 ring-black/[0.08] dark:ring-white/[0.1] shadow-sm focus-visible:ring-2 focus-visible:ring-primary/40",ms="rounded-xl bg-card/60 backdrop-blur-xl border-0 ring-1 ring-black/[0.08] dark:ring-white/[0.1] shadow-sm";function us({data:t,onChange:s,onSaveDraft:a,onSaveAndPrint:n,onSendForSignature:i,contractAlreadySent:l=!1,onDelete:m,saving:u,sending:b=!1,isEdit:y,isAdmin:M,isSuperAdmin:S,allInvoicesPaid:f,anyInvoicePaid:_,channels:O=[]}){var he,ge,Pe,De,be,de,ye;const[$,X]=v.useState(!1),[te,W]=v.useState(!1),[J,d]=v.useState(""),[w,r]=v.useState(null),L=v.useRef(null),x=(o,P)=>s({...t,[o]:P}),K=(o,P)=>{const Y=z(o);if(!o||!Ve(Y))return{};if(P==="three"){const V=re(Y,4),ae=re(V,8);return{payment_date_2:E(V,"yyyy-MM-dd"),payment_date_3:E(ae,"yyyy-MM-dd")}}if(P==="two"){const V=re(Y,12);return{payment_date_2:E(V,"yyyy-MM-dd")}}return{}},ie=o=>{const P=z(o);if(o&&Ve(P)){const Y=Ce(P,5),V=K(o,t.payment_variant);s({...t,contract_date:o,contract_end_date:E(Y,"yyyy-MM-dd"),contract_video_count:"25",payment_date_1:o,...V.payment_date_2?{payment_date_2:V.payment_date_2}:{},...V.payment_date_3?{payment_date_3:V.payment_date_3}:{}}),X(!1)}else x("contract_date",o)},ce=o=>{s({...t,payment_date_1:o,...K(o,t.payment_variant)})},Me=o=>{s({...t,payment_variant:o,...K(t.payment_date_1,o)})},je=o=>{o&&!window.confirm("Are you sure you want to override the contract term? It is usually calculated automatically.")||X(o)},ve=t.status==="completed",se=t.status==="cancelled",R=ve||se,Q=R||!!_,Z=()=>{s({...t,status:"completed"}),W(!1),d(""),r(null)};return e.jsxs("div",{className:"space-y-8",children:[ve&&e.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-3.5 rounded-2xl bg-green-500/10 ring-1 ring-green-500/20 text-green-600 dark:text-green-400 font-medium text-sm backdrop-blur-xl",children:[e.jsx(_e,{className:"w-4 h-4"})," Contract completed — read-only"]}),se&&e.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-3.5 rounded-2xl bg-destructive/10 ring-1 ring-destructive/20 text-destructive font-medium text-sm backdrop-blur-xl",children:[e.jsx(Tt,{className:"w-4 h-4"})," Contract cancelled"]}),e.jsxs("div",{className:"rounded-2xl bg-card/60 backdrop-blur-xl ring-1 ring-black/[0.06] dark:ring-white/[0.08] shadow-lg shadow-black/5 p-6 space-y-5",children:[e.jsx("h3",{className:"font-semibold text-lg tracking-tight",children:"Client Details"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Full Name *"}),e.jsx(T,{value:t.client_name,onChange:o=>x("client_name",o.target.value),placeholder:"John Doe",disabled:Q,className:U})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Company *"}),e.jsx(T,{value:t.client_company,onChange:o=>x("client_company",o.target.value),placeholder:"Acme Corp",required:!0,disabled:Q,className:U})]}),e.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Address *"}),e.jsx(T,{value:t.client_address,onChange:o=>x("client_address",o.target.value),placeholder:"123 Main St, City, Country",disabled:Q,className:U})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Email *"}),e.jsx(T,{type:"email",value:t.client_email,onChange:o=>x("client_email",o.target.value),placeholder:"[email protected]",disabled:Q,className:U})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Passport / ID"}),e.jsx(T,{value:t.client_id_number,onChange:o=>x("client_id_number",o.target.value),placeholder:"AB1234567",disabled:Q,className:U})]})]})]}),e.jsxs("div",{className:"rounded-2xl bg-card/60 backdrop-blur-xl ring-1 ring-black/[0.06] dark:ring-white/[0.08] shadow-lg shadow-black/5 p-6 space-y-5",children:[e.jsx("h3",{className:"font-semibold text-lg tracking-tight",children:"Contract Settings"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Channel"}),e.jsxs(Dt,{value:t.channel_id||"_none",onValueChange:o=>x("channel_id",o==="_none"?"":o),children:[e.jsx(At,{disabled:Q,className:ms,children:e.jsx(Et,{placeholder:"Select channel..."})}),e.jsxs(Lt,{children:[e.jsx(ze,{value:"_none",children:"— Not linked —"}),O.map(o=>e.jsx(ze,{value:o.id,children:o.name},o.id))]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Contract Language"}),e.jsx(Je,{options:[{value:"en",label:"English"},{value:"ru",label:"Russian"}],value:t.language,onChange:o=>x("language",o),disabled:Q})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Contract Date"}),e.jsx(T,{type:"date",value:t.contract_date,onChange:o=>ie(o.target.value),disabled:Q,className:U})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(D,{className:"flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:["Valid Until",!$&&e.jsx(Ke,{className:"w-3 h-3 text-muted-foreground"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer",children:[e.jsx(pt,{checked:$,onCheckedChange:je,className:"h-3.5 w-3.5"}),"Override"]})]}),e.jsx(T,{type:"date",value:t.contract_end_date,onChange:o=>x("contract_end_date",o.target.value),disabled:!$,className:Fe(U,!$&&"opacity-60")})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Video Count"}),e.jsx(T,{type:"number",min:"0",value:t.contract_video_count,onChange:o=>x("contract_video_count",o.target.value),disabled:Q,className:U})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Payment Plan"}),y?e.jsxs("div",{className:"flex items-center gap-2 rounded-2xl bg-black/[0.03] dark:bg-white/[0.04] ring-1 ring-black/[0.06] dark:ring-white/[0.08] px-4 py-2.5 text-sm",children:[e.jsx(Ke,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:t.payment_variant==="full"?"100%":t.payment_variant==="two"?"50/50":"40/30/30"}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:"Locked after save"})]}):e.jsx(Je,{options:[{value:"full",label:"100%"},{value:"two",label:"50/50"},{value:"three",label:"40/30/30"}],value:t.payment_variant,onChange:o=>Me(o)})]}),e.jsxs("div",{className:"rounded-2xl bg-black/[0.02] dark:bg-white/[0.03] ring-1 ring-black/[0.04] dark:ring-white/[0.06] p-4 space-y-1.5",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground uppercase tracking-wider",children:"Paid Term (auto)"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Until: "}),e.jsx("span",{className:"font-medium",children:t.paid_end_date||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Videos: "}),e.jsx("span",{className:"font-medium",children:t.paid_video_count??0})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Payment 1 Date"}),e.jsx(T,{type:"date",value:t.payment_date_1,onChange:o=>ce(o.target.value),disabled:Q,className:U})]}),(t.payment_variant==="two"||t.payment_variant==="three")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Payment 2 Date"}),e.jsx(T,{type:"date",value:t.payment_date_2,onChange:o=>x("payment_date_2",o.target.value),disabled:Q,className:U})]}),t.payment_variant==="three"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Payment 3 Date"}),e.jsx(T,{type:"date",value:t.payment_date_3,onChange:o=>x("payment_date_3",o.target.value),disabled:Q,className:U})]})]}
6),y&&t.status!=="cancelled"&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(q,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive rounded-xl",onClick:()=>{window.confirm("Are you sure you want to cancel this contract?")&&x("status","cancelled")},children:"Cancel Contract"})}),t.status==="cancelled"&&e.jsx("div",{className:"rounded-2xl bg-destructive/10 ring-1 ring-destructive/20 p-4 text-sm text-destructive font-medium",children:"❌ Contract Cancelled"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Notes (internal)"}),e.jsx(ht,{value:t.notes,onChange:o=>x("notes",o.target.value),placeholder:"Team comments...",rows:3,className:Fe(U,"min-h-[80px]")})]})]}),e.jsxs("div",{className:"rounded-2xl bg-card/60 backdrop-blur-xl ring-1 ring-black/[0.06] dark:ring-white/[0.08] shadow-lg shadow-black/5 p-6 space-y-5",children:[e.jsx("h3",{className:"font-semibold text-lg tracking-tight",children:"Company Representative"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Name *"}),e.jsx(T,{value:t.signer_name,onChange:o=>x("signer_name",o.target.value),placeholder:"Jane Smith",disabled:R,className:U})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Position"}),e.jsx(T,{value:t.signer_position,onChange:o=>x("signer_position",o.target.value),placeholder:"CEO",disabled:R,className:U})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(D,{className:"text-xs font-medium text-muted-foreground",children:"Email *"}),e.jsx(T,{type:"email",value:t.signer_email,onChange:o=>x("signer_email",o.target.value),placeholder:"[email protected]",disabled:R,className:U})]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-2",children:[!R&&e.jsxs(e.Fragment,{children:[e.jsxs(q,{onClick:a,disabled:u||!t.client_name.trim()||!((he=t.client_email)!=null&&he.trim())||!((ge=t.client_address)!=null&&ge.trim()),variant:"outline",className:"rounded-2xl",children:[e.jsx(Ut,{className:"w-4 h-4 mr-1.5"}),"Save Draft"]}),e.jsxs(q,{onClick:n,disabled:u||!t.client_name.trim()||!((Pe=t.client_email)!=null&&Pe.trim())||!((De=t.client_address)!=null&&De.trim()),variant:"outline",className:"rounded-2xl",children:[e.jsx(Te,{className:"w-4 h-4 mr-1.5"}),"Save & Print"]}),i&&y&&e.jsx(q,{onClick:i,disabled:l||u||b||!t.client_name.trim()||!((be=t.client_email)!=null&&be.trim())||!((de=t.signer_name)!=null&&de.trim())||!((ye=t.signer_email)!=null&&ye.trim()),className:"rounded-2xl",children:b?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-4 h-4 mr-1.5 border-2 border-current border-t-transparent rounded-full animate-spin inline-block"}),"Sending..."]}):l?e.jsxs(e.Fragment,{children:[e.jsx(_e,{className:"w-4 h-4 mr-1.5"}),"Sent"]}):e.jsxs(e.Fragment,{children:[e.jsx(Xe,{className:"w-4 h-4 mr-1.5"}),"Send for Signature"]})})]}),R&&e.jsxs(q,{onClick:n,disabled:u,variant:"outline",className:"rounded-2xl",children:[e.jsx(Te,{className:"w-4 h-4 mr-1.5"}),"Print"]}),y&&!R&&S&&e.jsx(e.Fragment,{children:f&&e.jsxs(q,{variant:"outline",onClick:()=>W(!0),disabled:u,className:"text-green-600 hover:text-green-700 border-green-200 hover:border-green-300 rounded-2xl",children:[e.jsx(_e,{className:"w-4 h-4 mr-1.5"}),"Complete Work"]})}),y&&m&&!R&&e.jsx(q,{variant:"ghost",size:"icon",onClick:m,className:"text-destructive hover:text-destructive ml-auto rounded-2xl",children:e.jsx(Bt,{className:"w-4 h-4"})})]}),e.jsx(gt,{open:te,onOpenChange:o=>{var P;W(o),o||(d(""),r(null),(P=L.current)==null||P.reset())},children:e.jsxs(bt,{children:[e.jsxs(yt,{children:[e.jsxs(_t,{children:['Complete Work for "',t.client_name,'"?']}),e.jsxs(ft,{className:"space-y-3",children:[e.jsx("span",{className:"block",children:"This will mark the contract as completed and make it read-only. This action cannot be undone."}),e.jsxs("span",{className:"block text-sm",children:["Type ",e.jsx("strong",{className:"text-foreground font-semibold select-all",children:t.client_name})," to confirm:"]})]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsx(T,{value:J,onChange:o=>d(o.target.value),placeholder:"Enter client name",autoComplete:"off"}),e.jsx(Ft,{ref:L,onVerify:o=>r(o),onExpire:()=>r(null),onError:()=>r(null)})]}),e.jsxs(jt,{children:[e.jsx(vt,{children:"Cancel"}),e.jsxs(Nt,{className:"bg-green-600 text-white hover:bg-green-700",disabled:J!==t.client_name||!w,onClick:Z,children:[e.jsx(_e,{className:"w-4 h-4 mr-1.5"}),"Complete Work"]})]})]})})]})}
6function ke(t){return"$"+t.toLocaleString("en-US")}function xs({services:t,content:s}){const a=s.tableHeaders;let n=0;const i=[1,2,3];return e.jsxs("table",{className:"w-full text-sm border-collapse print:text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/60",children:[e.jsx("th",{className:"border border-border px-2 py-1.5 text-left w-8",children:a.index}),e.jsx("th",{className:"border border-border px-2 py-1.5 text-left",children:a.service}),e.jsx("th",{className:"border border-border px-2 py-1.5 text-center w-16",children:a.unit}),e.jsx("th",{className:"border border-border px-2 py-1.5 text-center w-10",children:a.qty}),e.jsx("th",{className:"border border-border px-2 py-1.5 text-right w-20",children:a.unitPrice}),e.jsx("th",{className:"border border-border px-2 py-1.5 text-right w-20",children:a.total})]})}),e.jsxs("tbody",{children:[i.map(l=>{const m=t.filter(b=>b.stage===l),u=Kt(t,l);return e.jsxs(v.Fragment,{children:[e.jsx("tr",{className:"bg-primary/5",children:e.jsxs("td",{colSpan:6,className:"border border-border px-2 py-2 font-semibold text-foreground text-xs",children:[s.stageLabels[l-1]," — ",ke(u),e.jsxs("span",{className:"ml-2 text-[10px] font-normal text-muted-foreground",children:["(",s.stageDurations[l-1],")"]})]})}),m.map(b=>(n++,e.jsxs("tr",{children:[e.jsx("td",{className:"border border-border px-2 py-1 text-muted-foreground text-xs",children:n}),e.jsx("td",{className:"border border-border px-2 py-1 text-xs",children:b.name}),e.jsx("td",{className:"border border-border px-2 py-1 text-center text-muted-foreground text-xs",children:b.unit}),e.jsx("td",{className:"border border-border px-2 py-1 text-center text-xs",children:b.qty}),e.jsx("td",{className:"border border-border px-2 py-1 text-right tabular-nums text-xs",children:ke(b.unitPrice)}),e.jsx("td",{className:"border border-border px-2 py-1 text-right tabular-nums font-medium text-xs",children:ke(Math.round(b.unitPrice*b.qty))})]},`${l}-${n}`)))]},l)}),e.jsxs("tr",{className:"bg-primary/10 font-bold",children:[e.jsx("td",{colSpan:5,className:"border border-border px-2 py-2 text-right text-sm",children:s.totalLabel}),e.jsx("td",{className:"border border-border px-2 py-2 text-right tabular-nums text-sm",children:ke(Qt(t))})]})]})]})}function Ze({formData:t,contractNumber:s}){const a=t.language==="ru"?Ot:$t,n=Rt(t.language),i=t.payment_variant,l=a.paymentVariants[i];return e.jsxs("div",{id:"contract-preview",className:"bg-white text-black p-6 sm:p-8 space-y-6 text-sm print:p-4 print:text-xs",children:[e.jsxs("div",{className:"text-center space-y-1 pb-4 border-b border-gray-300",children:[e.jsx("h1",{className:"text-xl font-bold",children:a.title}),e.jsx("p",{className:"text-gray-600 text-xs",children:a.subtitle}),s&&e.jsxs("p",{className:"text-xs font-mono text-gray-500",children:["№ ",s]}),e.jsxs("p",{className:"text-xs text-gray-500",children:[t.language==="ru"?"Дата:":"Date:"," ",t.contract_date||"___________"]}),t.contract_end_date&&e.jsxs("p",{className:"text-xs text-gray-500",children:[t.language==="ru"?"Общий срок действия:":"Total term:"," ",t.contract_date||"—"," — ",t.contract_end_date]}),t.paid_end_date&&e.jsxs("p",{className:"text-xs text-gray-600 font-medium",children:[t.language==="ru"?"Оплаченный срок:":"Paid term:"," ",t.contract_date||"—"," — ",t.paid_end_date]}),t.contract_video_count&&e.jsxs("p",{className:"text-xs text-gray-500",children:[t.language==="ru"?"Видео по контракту:":"Videos under contract:"," ",t.paid_video_count??0," / ",t.contract_video_count]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[e.jsx("div",{className:"text-xs text-gray-600 space-y-0.5",children:a.companyBlock.map((m,u)=>e.jsx("p",{className:u===0?"font-semibold text-black":"",children:m},u))}),e.jsxs("div",{className:"text-xs text-gray-600 space-y-0.5",children:[e.jsx("p",{className:"font-semibold text-black",children:t.language==="ru"?"ЗАКАЗЧИК:":"CLIENT:"}),t.client_name&&e.jsx("p",{children:t.client_name}),t.client_company&&e.jsx("p",{children:t.client_company}),t.client_address&&e.jsx("p",{children:t.client_address}),t.client_email&&e.jsx("p",{children:t.client_email}),t.client_id_number&&e.jsxs("p",{children:[(t.language==="ru","ID:")," ",t.client_id_number]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"font-semibold",children:l.label}),e.jsx("p",{className:"text-xs text-gray-600",children:l.description}),e.jsxs("table",{className:"w-full text-xs border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-gray-100",children:[e.jsx("th",{className:"border border-gray-300 px-2 py-1 text-left",children:"Step"}),e.jsx("th",{className:"border border-gray-300 px-2 py-1 text-right",children:"Amount"}),e.jsx("th",{className:"border border-gray-300 px-2 py-1 text-left",children:"When"})]})}
6),e.jsx("tbody",{children:l.schedule.map((m,u)=>{const b=`payment_date_${u+1}`,y=t[b];return e.jsxs("tr",{children:[e.jsx("td",{className:"border border-gray-300 px-2 py-1 font-medium",children:m.step}),e.jsx("td",{className:"border border-gray-300 px-2 py-1 text-right tabular-nums font-semibold",children:m.amount}),e.jsx("td",{className:"border border-gray-300 px-2 py-1 text-gray-600",children:y||m.when})]},u)})})]})]}),e.jsx(xs,{services:n,content:a}),a.sections.map((m,u)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("h2",{className:"text-sm font-semibold",children:m.heading}),m.paragraphs.map((b,y)=>e.jsx("p",{className:"text-xs text-gray-700 leading-relaxed whitespace-pre-line",children:b},y))]},u)),e.jsxs("div",{className:"border border-gray-300 rounded p-3",children:[e.jsx("h3",{className:"font-semibold text-xs mb-2",children:a.bankDetails.label}),e.jsx("div",{className:"grid gap-1 text-xs",children:a.bankDetails.rows.map((m,u)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("span",{className:"text-gray-500 min-w-[120px]",children:[m.label,":"]}),e.jsx("span",{className:"font-medium",children:m.value})]},u))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-8 pt-6 border-t border-gray-300 print-signature-block",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-bold text-xs uppercase tracking-wider",children:a.signatureBlock.companyLabel}),e.jsx("p",{className:"text-xs text-gray-500",children:"WINER MEDIA FZCO"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 mb-1",children:a.signatureBlock.nameLabel}),t.signer_name?e.jsxs("p",{className:"text-xs font-medium",children:[t.signer_name,t.signer_position?`, ${t.signer_position}`:""]}):e.jsx("div",{className:"border-b border-gray-400 h-6"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 mb-1",children:a.signatureBlock.signLabel}),e.jsx("div",{className:"border-b border-gray-400 h-12"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 mb-1",children:a.signatureBlock.dateLabel}),e.jsx("p",{className:"text-xs",children:t.contract_date||"___________"})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-bold text-xs uppercase tracking-wider",children:a.signatureBlock.clientLabel}),t.client_name&&e.jsx("p",{className:"text-xs text-gray-500",children:t.client_name}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 mb-1",children:a.signatureBlock.nameLabel}),t.client_name?e.jsx("p",{className:"text-xs font-medium",children:t.client_name}):e.jsx("div",{className:"border-b border-gray-400 h-6"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 mb-1",children:a.signatureBlock.signLabel}),e.jsx("div",{className:"border-b border-gray-400 h-12"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-gray-500 mb-1",children:a.signatureBlock.dateLabel}),e.jsx("div",{className:"border-b border-gray-400 h-6"})]})]})]})]})]})}const Ye={1:{en:"Stage 1 — Setup: Strategy consultation, content strategy, AI avatar creation, voice clone setup, infrastru
6cture setup",ru:"Этап 1 — Настройка: Стратегическая консультация, контент-стратегия, создание AI аватара, клонирование голоса, настройка инфраструктуры"},2:{en:"Stage 2 — Launch: Script writing, voiceover generation, video editing & post-production, thumbnail design (5 videos)",ru:"Этап 2 — Запуск: Написание сценариев, генерация озвучки, видеомонтаж и постпродакшн, дизайн превью (5 видео)"},3:{en:"Stage 3 — Growth: Script writing, voiceover generation, video editing & post-production, thumbnail design, SEO optimization (20 videos)",ru:"Этап 3 — Рост: Написание сценариев, генерация озвучки, видеомонтаж и постпродакшн, дизайн превью, SEO оптимизация (20 видео)"}};function ps({invoice:t,formData:s,contractNumber:a}){var m,u;const n=s.language||"en",i=t.due_date?E(z(t.due_date),"MMMM dd, yyyy"):E(new Date,"MMMM dd, yyyy"),l=((m=Ye[t.stage])==null?void 0:m[n])||((u=Ye[t.stage])==null?void 0:u.en)||`Stage ${t.stage}`;return e.jsxs("div",{className:"w-[210mm] min-h-[297mm] mx-auto bg-white text-black p-[15mm] text-[11pt] leading-relaxed font-sans print:p-[10mm]",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsx("h1",{className:"text-2xl font-bold tracking-wide text-black",children:"COMMERCIAL INVOICE"}),e.jsxs("p",{className:"text-lg font-semibold mt-1 text-black",children:["#",t.invoice_number]}),e.jsx("p",{className:"text-sm text-gray-600 mt-1",children:i})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-6 mb-6",children:[e.jsxs("div",{className:"border border-gray-300 p-3 rounded",children:[e.jsx("h3",{className:"font-bold text-sm mb-2 text-black",children:"Issued By:"}),e.jsx("p",{className:"font-semibold text-black",children:"WINER MEDIA FZCO"}),e.jsxs("p",{className:"text-sm text-gray-700",children:["Address: DSO – IFZA, IFZA Properties,",e.jsx("br",{}),"Dubai Silicon Oasis, Dubai, UAE"]}),e.jsx("p",{className:"text-sm text-gray-700 mt-1",children:"E-mail: [email protected]"})]}),e.jsxs("div",{className:"border border-gray-300 p-3 rounded",children:[e.jsx("h3",{className:"font-bold text-sm mb-2 text-black",children:"Bank Details:"}),e.jsxs("p",{className:"text-sm text-gray-700",children:[e.jsx("span",{className:"font-medium text-black",children:"Bank:"})," Mashreq Bank",e.jsx("br",{}),e.jsx("span",{className:"font-medium text-black",children:"IBAN:"})," AE350330000019200055498",e.jsx("br",{}),e.jsx("span",{className:"font-medium text-black",children:"SWIFT:"})," BOMLAEAD",e.jsx("br",{}),e.jsx("span",{className:"font-medium text-black",children:"Beneficiary:"})," WINER MEDIA FZCO"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-6 mb-6",children:[e.jsxs("div",{className:"border border-gray-300 p-3 rounded",children:[e.jsx("h3",{className:"font-bold text-sm mb-2 text-black",children:"Bill To:"}),e.jsx("p",{className:"font-semibold text-black",children:s.client_company||s.client_name}),s.client_address&&e.jsxs("p",{className:"text-sm text-gray-700",children:["Address: ",s.client_address]}),s.client_email&&e.jsxs("p",{className:"text-sm text-gray-700",children:["E-mail: ",s.client_email]}),s.client_id_number&&e.jsxs("p",{className:"text-sm text-gray-700",children:["ID: ",s.client_id_number]})]}),e.jsxs("div",{className:"border border-gray-300 p-3 rounded",children:[e.jsx("h3",{className:"font-bold text-sm mb-2 text-black",children:"Ship To:"}),e.jsx("p",{className:"font-semibold text-black",children:s.client_company||s.client_name}),e.jsxs("p",{className:"text-sm text-gray-700",children:["Contact Person: ",s.client_name]}),s.client_email&&e.jsxs("p",{className:"text-sm text-gray-700",children:["E-mail: ",s.client_email]}),e.jsxs("p",{className:"text-sm text-gray-700 mt-1",children:["Payment Terms: ",n==="ru"?"Оплата по выставлению":"Payment on Delivery"]})]})]}),a&&e.jsxs("p",{className:"text-sm text-gray-600 mb-4",children:[n==="ru"?"Согласно договору":"According to agreement"," #",a]}),e.jsxs("table",{className:"w-full border-collapse mb-6 text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-gray-100",children:[e.jsx("th",{className:"border border-gray-300 px-3 py-2 text-left w-8 text-black",children:"#"}),e.jsx("th",{className:"border border-gray-300 px-3 py-2 text-left text-black",children:"Description"}),e.jsx("th",{className:"border border-gray-300 px-3 py-2 text-center w-16 text-black",children:"Qty"}),e.jsx("th",{className:"border border-gray-300 px-3 py-2 text-center w-12 text-black",children:"UOM"}),e.jsx("th",{className:"border border-gray-300 px-3 py-2 text-right w-24 text-black",children:"Price (USD)"}),e.jsx("th",{className:"border border-gray-300 px-3 py-2 text-right w-28 text-black",children:"Amount (USD)"})]})}),e.jsx("tbody",{children:e.jsxs("tr",{children:[e.jsx("td",{className:"border border-gray-300 px-3 py-2 text-black",children:"1"}),e.jsx("td",{className:"border border-gray-300 px-3 py-2 text-black",children:l}),e.jsx("td",{className:"border border-gray-300 px-3 py-2 text-center text-black",children:"1"}),e.jsx("td",{className:"border border-gray-300 px-3 py-2 text-center text-black",children:"Pcs"}),e.jsx("td",{className:"border border-gray-300 px-3 py-2 text-right tabular-nums text-black",children:Number(t.amount).toLocaleStr
6ing("en-US",{minimumFractionDigits:2})}),e.jsx("td",{className:"border border-gray-300 px-3 py-2 text-right tabular-nums font-semibold text-black",children:Number(t.amount).toLocaleString("en-US",{minimumFractionDigits:2})})]})}),e.jsx("tfoot",{children:e.jsxs("tr",{className:"bg-gray-50",children:[e.jsx("td",{colSpan:4}),e.jsx("td",{className:"border border-gray-300 px-3 py-2 text-right font-bold text-black",children:"Total (USD):"}),e.jsx("td",{className:"border border-gray-300 px-3 py-2 text-right font-bold tabular-nums text-black",children:Number(t.amount).toLocaleString("en-US",{minimumFractionDigits:2})})]})})]})]})}const hs=t=>{switch(t){case 1:return"Stage 1 — Setup";case 2:return"Stage 2 — Launch";case 3:return"Stage 3 — Growth";default:return`Stage ${t}`}},gs={draft:{label:"Draft",variant:"outline"},sent:{label:"Sent",variant:"secondary"},delivered:{label:"Delivered",variant:"secondary"},signed:{label:"Signed ✓",variant:"default"},declined:{label:"Declined",variant:"destructive"},voided:{label:"Voided",variant:"destructive"}};function bs({invoices:t,onTogglePaid:s,loading:a,formData:n,contractNumber:i,canTogglePaid:l=!1,documents:m=[],onSendInvoice:u,sendingInvoiceId:b}){if(!t.length)return null;const y=f=>m.find(_=>_.invoice_id===f),M=async f=>{try{const _=await st(f);window.open(_,"_blank")}catch(_){A({title:"Error",description:_.message,variant:"destructive"})}},S=f=>{if(!n||!i)return;const _=window.open("","_blank");if(!_)return;const O=document.createElement("div"),$=kt(O);$.render(e.jsx(ps,{invoice:f,formData:n,contractNumber:i})),setTimeout(()=>{const X=O.innerHTML;$.unmount(),_.document.write(`<!DOCTYPE html><html><head>
7        <title>Invoice ${f.invoice_number}</title>
8        <script src="https://cdn.tailwindcss.com"><\/script>
9        <style>
10          @media print { body { margin: 0; } @page { size: A4; margin: 10mm; } }
11          body { font-family: system-ui, -apple-system, sans-serif; }
12        </style>
13      </head><body>${X}</body></html>`),_.document.close(),setTimeout(()=>_.print(),500)},100)};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(Vt,{className:"w-5 h-5"}),"Invoices"]}),e.jsxs("table",{className:"w-full text-sm border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/60",children:[e.jsx("th",{className:"border border-border px-3 py-2 text-left",children:"№"}),e.jsx("th",{className:"border border-border px-3 py-2 text-left",children:"Stage"}),e.jsx("th",{className:"border border-border px-3 py-2 text-right",children:"Amount"}),e.jsx("th",{className:"border border-border px-3 py-2 text-center",children:"Date"}),e.jsx("th",{className:"border border-border px-3 py-2 text-center",children:"Paid"}),e.jsx("th",{className:"border border-border px-3 py-2 text-center",children:"DocuSign"})]})}),e.jsx("tbody",{children:t.map(f=>{const _=y(f.id),O=_?gs[_.status]||{label:_.status,variant:"outline"}:null;return f.id,e.jsxs("tr",{className:f.paid?"bg-green-500/5":"",children:[e.jsx("td",{className:"border border-border px-3 py-1.5 font-mono text-xs",children:f.invoice_number}),e.jsx("td",{className:"border border-border px-3 py-1.5",children:hs(f.stage)}),e.jsxs("td",{className:"border border-border px-3 py-1.5 text-right tabular-nums font-semibold",children:["$",Number(f.amount).toLocaleString("en-US")]}),e.jsx("td",{className:"border border-border px-3 py-1.5 text-center text-muted-foreground",children:f.due_date?E(z(f.due_date),"dd.MM.yyyy"):"—"}),e.jsx("td",{className:"border border-border px-3 py-1.5 text-center",children:l?e.jsx(wt,{checked:f.paid,onCheckedChange:$=>s(f.id,$),disabled:a}):e.jsx("span",{className:f.paid?"text-green-600 font-medium":"text-muted-foreground",children:f.paid?"✓":"—"})}),e.jsx("td",{className:"border border-border px-3 py-1.5 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[O&&e.jsx(Se,{variant:O.variant,className:"text-[10px] px-1.5 py-0",children:O.label}),(_==null?void 0:_.signed_pdf_url)&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>M(_.signed_pdf_url),title:"View signed PDF",children:e.jsx(Ue,{className:"w-3 h-3"})}),n&&i&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>S(f),title:"Print / Download invoice",children:e.jsx(Te,{className:"w-3.5 h-3.5"})}),!_&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"📎 With contract"})]})})]},f.id)})})]})]})}const ys={draft:{label:"Draft",variant:"outline"},sent:{label:"Sent",variant:"secondary"},delivered:{label:"Delivered",variant:"secondary"},signed:{label:"Signed ✓",variant:"default"},declined:{label:"Declined",variant:"destructive"},voided:{label:"Voided",variant:"destructive"}};function _s(t){const s=new Map;for(const n of t){const i=s.get(n.doc_number)||[];i.push(n),s.set(n.doc_number,i)}const a=[];for(const[,n]of s){n.sort((l,m)=>new Date(m.created_at).getTime()-new Date(l.created_at).getTime());const i=n.find(l=>l.envelope_id);a.push(i||n[0])}return a.sort((n,i)=>new Date(i.created_at).getTime()-new Date(n.created_at).getTime()),a}const at={created:"⏳ Waiting",sent:"📧 Sent",delivered:"📬 Opened",completed:"✅ Signed",signed:"✅ Signed",declined:"❌ Declined",autoresponded:"📧 Sent"},nt={created:"⏳ Pending",sent:"📧 Copy sent",delivered:"📬 Copy delivered",completed:"📬 Copy delivered",autoresponded:"📧 Copy sent"};function fs({r:t}){const s=t.role==="copy",a=t.role==="company"?"Company":t.role==="client"?"Client":"Copy",n=s?nt[t.status]||t.status:at[t.status]||t.status;return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"font-medium min-w-[70px]",children:[a,":"]}),e.jsx("span",{className:"text-muted-foreground truncate max-w-[140px]",title:t.email,children:t.email}),e.jsx("span",{children:n}),!s&&t.signedDateTime&&e.jsx("span",{className:"text-muted-foreground",children:E(z(t.signedDateTime),"dd.MM HH:mm")}
13)]})}function js({documents:t,contractId:s,onResend:a,resending:n}){const i=ds(),l=os(),m=ls(),u=v.useRef(null),[b,y]=v.useState(null),[M,S]=v.useState(null),[f,_]=v.useState({}),O=_s(t);if(!O.length)return e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ie,{className:"w-10 h-10 mx-auto mb-2 opacity-30"}),e.jsx("p",{className:"text-sm",children:"No documents sent yet"})]});const $=async d=>{try{const w=await st(d);window.open(w,"_blank")}catch(w){A({title:"Error",description:w.message,variant:"destructive"})}},X=async d=>{var w;S(d);try{const r=await i.mutateAsync(d);(w=r.recipients)!=null&&w.length&&_(x=>({...x,[d]:r.recipients}));const L=r.recipients.map(x=>{const K=x.role==="company"?"🏢":x.role==="copy"?"📋":"👤",ce=x.role==="copy"?nt[x.status]||x.status:at[x.status]||x.status;return`${K} ${x.name}: ${ce}`}).join(`
14`);A({title:`Status: ${r.status}`,description:L||`Envelope: ${r.envelope_status}`})}catch(r){A({title:"Check failed",description:r.message,variant:"destructive"})}finally{S(null)}},te=async d=>{try{await m.mutateAsync(d),A({title:"Sent",description:"Notifications resent to all pending signers"})}catch(w){A({title:"Error",description:w.message,variant:"destructive"})}},W=d=>{var w;y(d),(w=u.current)==null||w.click()},J=async d=>{var r;const w=(r=d.target.files)==null?void 0:r[0];if(!(!w||!b||!s))try{await l.mutateAsync({documentId:b,file:w,contractId:s}
14),A({title:"Document uploaded",description:"Signed PDF saved to archive"})}catch(L){A({title:"Upload error",description:L.message,variant:"destructive"})}finally{y(null),u.current&&(u.current.value="")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(Ie,{className:"w-5 h-5"}),"Document Archive"]}),e.jsx("input",{ref:u,type:"file",accept:".pdf",className:"hidden",onChange:J}),e.jsxs("table",{className:"w-full text-sm border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/60",children:[e.jsx("th",{className:"border border-border px-3 py-2 text-left",children:"Type"}),e.jsx("th",{className:"border border-border px-3 py-2 text-left",children:"Number"}),e.jsx("th",{className:"border border-border px-3 py-2 text-left",children:"Client"}),e.jsx("th",{className:"border border-border px-3 py-2 text-right",children:"Amount"}),e.jsx("th",{className:"border border-border px-3 py-2 text-center",children:"Status"}),e.jsx("th",{className:"border border-border px-3 py-2 text-center",children:"Date"}),e.jsx("th",{className:"border border-border px-3 py-2 text-center",children:"Actions"})]})}),e.jsx("tbody",{children:O.map(d=>{const w=ys[d.status]||{label:d.status,variant:"outline"},r=M===d.id,L=d.envelope_id&&d.status!=="signed"&&d.status!=="declined"&&d.status!=="voided",x=f[d.id];return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:d.status==="signed"?"bg-green-500/5":"",children:[e.jsx("td",{className:"border border-border px-3 py-1.5",children:d.doc_type==="invoice"?"📄 Invoice":"📋 Contract"}),e.jsx("td",{className:"border border-border px-3 py-1.5 font-mono text-xs",children:d.doc_number}),e.jsx("td",{className:"border border-border px-3 py-1.5",children:d.client_name}),e.jsx("td",{className:"border border-border px-3 py-1.5 text-right tabular-nums",children:d.amount?`$${Number(d.amount).toLocaleString("en-US")}`:"—"}),e.jsx("td",{className:"border border-border px-3 py-1.5 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Se,{variant:w.variant,className:"text-xs",children:w.label}),L&&e.jsx(Ge,{className:"w-3.5 h-3.5 text-warning"})]})}),e.jsx("td",{className:"border border-border px-3 py-1.5 text-center text-muted-foreground text-xs",children:d.sent_at?E(z(d.sent_at),"dd.MM.yyyy HH:mm"):E(z(d.created_at),"dd.MM.yyyy")}),e.jsx("td",{className:"border border-border px-3 py-1.5 text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[d.signed_pdf_url&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>$(d.signed_pdf_url),title:"View signed PDF",children:e.jsx(Ue,{className:"w-3.5 h-3.5"})}),d.envelope_id&&d.status!=="signed"&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>X(d.id),disabled:r,title:"Check DocuSign status",children:r?e.jsx(me,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Ct,{className:"w-3.5 h-3.5"})}),L&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>te(d.id),disabled:m.isPending,title:"Resend notifications to signers",children:m.isPending?e.jsx(me,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Ht,{className:"w-3.5 h-3.5"})}),!d.signed_pdf_url&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>W(d.id),disabled:l.isPending,title:"Upload signed PDF manually",children:l.isPending&&b===d.id?e.jsx(me,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(zt,{className:"w-3.5 h-3.5"})}),(d.status==="declined"||d.status==="voided")&&a&&e.jsx(q,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>a(d.id),disabled:n,title:"Resend",children:n?e.jsx(me,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Xe,{className:"w-3.5 h-3.5"})})]})})]},d.id),x&&x.length>0&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"border border-border px-4 py-2 bg-muted/30",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Recipients:"}),x.map((K,ie)=>e.jsx(fs,{r:K},ie))]})})},`${d.id}-recipients`)]})})})]})]})}const Le={client_name:"",client_company:"",client_address:"",client_email:"",client_id_number:"",language:"en",payment_variant:"three",contract_date:new Date().toISOString().split("T")[0],contract_end_date:"",contract_video_count:"",payment_date_1:"",payment_date_2:"",payment_date_3:"",notes:"",status:"draft",signer_name:"",signer_position:"",signer_email:"",channel_id:"",paid_end_date:"",paid_video_count:0};function wa(){const{user:t}=pe(),{isAdmin:s,isSales:a,isSuperAdmin:n,loading:i}=St(),l=H(),[m,u]=It(),{channels:b,isLoading:y,createChannel:M}=Mt(),{data:S=[],isLoading:f}=Jt(),_=Zt(),O=Yt(),$=Gt(),X=ts(),te=as(),[W,J]=v.useState("list"),[d,w]=v.useState(null),[r,L]=v.useState(Le),[x,K]=v.useState(""),[ie,ce]=v.useState(!1),[Me,je]=v.useState(!1),[ve,se]=v.useState(!1),{data:R=[],isLoading:Q}=es(d),{data:Z=[]}=ns(d),he=is(),ge=cs(),[Pe,De]=v.useState(null),[be,de]=v.useState(null),ye=S.map(c=>c.id),{data:o}=ss(ye),{data:P}=rs(ye);v.useEffect(()=>{const c=()=>se(!0),j=()=>se(!1),g=window.matchMedia("print"),N=k=>se(k.matches);return window.addEventListener("beforeprint",c),window.addEventListener("afterprint",j),g.addEventListener?g.addEventListener("change",N):g.addListener(N),()=>{window.removeEventListener("beforeprint",c),window.removeEventListener("afterprint",j),g.removeEventListener?g.removeEventListener("change",N):g.removeListener(N)}},[]);const[Y,V]=v.useState(null);v.useEffect(()=>{const c=m.get("edit"),j=m.get("from_lead");if(c&&S.length>0){const g=S.find(N=>N.id===c);g&&(Re(g),u({},{replace:!0}))}else j&&!d&&(V(j),(async()=>{try{const{data:g,error:N}=await p.functions.invoke("manage-marketing-lead",{body:{action:"list"}});if(!N&&(g!=null&&g.leads)){const k=g.leads.find(h=>h.id===j);if(k){const h=new Date().toISOString().split("T")[0],ee=z(h),ne=E(Ce(ee,5),"yyyy-MM-dd"),le=E(re(ee,4),"yyyy-MM-dd"),oe=E(re(z(le),8),"yyyy-MM-dd");L({...Le,client_name:k.full_name||"",client_company:k.company||"",client_email:k.email||"",contract_date:h,contract_end_date:ne,contract_video_count:"25",payment_date_1:h,payment_date_2:le,payment_date_3:oe,paid_end_date:"",paid_video_count:0}),K(""),J("editor")}}}catch(g){console.error("Failed to fetch lead:",g)}})(),u({},{replace:!0}))},[m,S]);const ae=v.useCallback(async(c,j)=>{try{await p.functions.invoke("manage-marketing-lead",{body:{action:"update_status",leadI
14d:c,newStatus:j}})}catch(g){console.error("Failed to sync lead status:",g)}},[]),rt=s||a,it=y||f,$e=()=>{w(null);const c=new Date().toISOString().split("T")[0],j=z(c),g=E(Ce(j,5),"yyyy-MM-dd"),N=E(re(j,4),"yyyy-MM-dd"),k=E(re(z(N),8),"yyyy-MM-dd");L({...Le,contract_date:c,contract_end_date:g,contract_video_count:"25",payment_date_1:c,payment_date_2:N,payment_date_3:k,paid_end_date:"",paid_video_count:0}),K(""),J("editor")},Re=async c=>{var j;w(c.id),L({client_name:c.client_name,client_company:c.client_company||"",client_address:c.client_address||"",client_email:c.client_email||"",client_id_number:c.client_id_number||"",language:c.language,payment_variant:c.payment_variant,contract_date:c.contract_date,contract_end_date:c.contract_end_date||"",contract_video_count:((j=c.contract_video_count)==null?void 0:j.toString())||"",notes:c.notes||"",status:c.status,signer_name:c.signer_name||"",signer_position:c.signer_position||"",signer_email:c.signer_email||"",channel_id:c.channel_id||"",payment_date_1:c.payment_date_1||"",payment_date_2:c.payment_date_2||"",payment_date_3:c.payment_date_3||"",paid_end_date:c.paid_end_date||"",paid_video_count:c.paid_video_count??0}),K(c.contract_number),J("editor")},Ne=v.useCallback(async c=>{var j;if(!((j=r.client_company)!=null&&j.trim())){A({title:"Validation Error",description:"Company is required — it is used as the channel name.",variant:"destructive"});return}ce(!0);try{const g={client_name:r.client_name.trim(),client_company:r.client_company||null,client_address:r.client_address||null,client_email:r.client_email||null,client_id_number:r.client_id_number||null,language:r.language,payment_variant:r.payment_variant,contract_date:r.contract_date,contract_end_date:r.contract_end_date||null,contract_video_count:r.contract_video_count?parseInt(r.contract_video_count):null,notes:r.notes||null,status:r.status,signer_name:r.signer_name||null,signer_position:r.signer_position||null,signer_email:r.signer_email||null,payment_date_1:r.payment_date_1||null,payment_date_2:r.payment_date_2||null,payment_date_3:r.payment_date_3||null,paid_end_date:d&&r.paid_end_date||null,paid_video_count:d?r.paid_video_count??0:0,channel_id:r.channel_id||null};!d&&Y&&(g.lead_id=Y);let N=d,k=x;if(d){const h=await O.mutateAsync({id:d,...g});K(h.contract_number),k=h.contract_number}else{const h=await _.mutateAsync(g);N=h.id,w(h.id),K(h.contract_number),k=h.contract_number,Y&&(ae(Y,"contract_draft"),V(null))}if(N&&k){try{await X.mutateAsync({contractId:N,contractNumber:k,variant:r.payment_variant,paymentDates:[r.payment_date_1||null,r.payment_date_2||null,r.payment_date_3||null]})}catch(h){console.error("Invoice upsert failed:",h)}try{const{data:h}=await p.from("production_invoices").select("*").eq("contract_id",N).order("stage",{ascending:!0}),{data:ee}=await p.from("production_documents").select("status").eq("contract_id",N);if(h){const ne=(ee||[]).some(I=>I.status==="completed"||I.status==="signed"),le=r.status==="cancelled"||r.status==="completed"?r.status:void 0,oe=Ee(h,ne,le,r.payment_variant);await p.from("production_contracts").update({status:oe.key,updated_at:new Date().toISOString()}).eq("id",N)}}catch(h){console.error("Auto-sync status failed:",h)}}if(r.status==="completed"&&N){const{data:h}=await p.from("production_contracts").select("lead_id, channel_id").eq("id",N).single();if(h!=null&&h.lead_id&&ae(h.lead_id,"completed"),h!=null&&h.channel_id){const{data:ee}=await p.from("production_client_channels").select("client_id").eq("channel_id",h.channel_id);if(ee&&ee.length>0)for(const ne of ee)await p.from("production_clients").update({status:"churned",updated_at:new Date().toISOString()}).eq("id",ne.client_id);l.invalidateQueries({queryKey:["production-clients"]}),l.invalidateQueries({queryKey:["client-health-tasks"]}),l.invalidateQueries({queryKey:["client-health-tasks-all"]})}}c&&(se(!0),setTimeout(()=>window.print(),120))}catch(g){A({title:"Error",description:g.message,variant:"destructive"})}finally{ce(!1)}},[r,d,x,_,O,M,X]),ct=v.useCallback(async(c,j)=>{var g,N;try{if(await te.mutateAsync({invoiceId:c,paid:j}),d&&r.contract_date){const{data:k}=await p.from("production_invoices").select("*").eq("contract_id",d).order("stage",{ascending:!0});if(k){const h=Xt(k,r.contract_date,r.payment_variant),ne=(Z||[]).some(I=>I.status==="completed"||I.status==="signed"),le=r.status==="cancelled"||r.status==="completed"?r.status:void 0,oe=Ee(k,ne,le,r.payment_variant);if(await p.from("production_contracts").update({paid_end_date:h.paid_end_date,paid_video_count:h.paid_video_count,status:oe.key}
14).eq("id",d),l.invalidateQueries({queryKey:["production-channels"]}),l.invalidateQueries({queryKey:["production-invoices-batch"]}),l.invalidateQueries({queryKey:["production-contracts"]}),L(I=>({...I,paid_end_date:h.paid_end_date||"",paid_video_count:h.paid_video_count,status:oe.key})),j){const{data:I}=await p.from("production_contracts").select("channel_id, lead_id").eq("id",d).single();if(!(I!=null&&I.channel_id))try{const B=((g=r.client_company)==null?void 0:g.trim())||r.client_name.trim(),F=await M.mutateAsync({name:B,description:`Contract ${x||""}`.trim()});await p.from("production_contracts").update({channel_id:F.id}).eq("id",d),L(C=>({...C,channel_id:F.id})),A({title:"🎬 Channel created",description:B})}catch(B){console.error("Auto-create channel failed:",B)}try{let B=null;if(r.client_email){const{data:C}=await p.from("profiles").select("id").eq("email",r.client_email).maybeSingle();B=(C==null?void 0:C.id)||null}let F=null;if(B){const{data:C}=await p.from("production_clients").select("id").eq("user_id",B).maybeSingle();F=(C==null?void 0:C.id)||null}if(!F&&r.client_email){const{data:C}=await p.from("production_clients").select("id").eq("email",r.client_email).maybeSingle();F=(C==null?void 0:C.id)||null}if(!F){const{data:C}=await p.from("production_clients").insert({user_id:B,display_name:r.client_name,email:r.client_email||null,status:"active"}).select("id").single();F=(C==null?void 0:C.id)||null}if(F){const C=r.channel_id||((N=(await p.from("production_contracts").select("channel_id").eq("id",d).single()).data)==null?void 0:N.channel_id);if(C){const{data:we}=await p.from("production_client_channels").select("id").eq("client_id",F).eq("channel_id",C).maybeSingle();we||await p.from("production_client_channels").insert({client_id:F,channel_id:C,assigned_by:t==null?void 0:t.id})}l.invalidateQueries({queryKey:["production-clients"]}),l.invalidateQueries({queryKey:["client-channels"]}),l.invalidateQueries({queryKey:["all-client-channels"]})}}catch(B){console.error("Auto-create production_clients failed:",B)}I!=null&&I.lead_id&&k.filter(F=>F.paid).length===1&&ae(I.lead_id,"contract_paid")}else{const{data:I}=await p.from("production_contracts").select("lead_id").eq("id",d).single();if(I!=null&&I.lead_id&&k.filter(F=>F.paid).length===0){const C=(Z||[]).some(we=>we.status==="completed"||we.status==="signed");ae(I.lead_id,C?"contract_signed":"contract_draft")}}}}}catch(k){A({title:"Error",description:k.message,variant:"destructive"})}},[d,r.contract_date,r.client_company,r.client_name,r.payment_variant,r.status,x,te,M,l,Z,ae]),dt=v.useCallback(async()=>{if(!d||!r.client_email){A({title:"Error",description:"Client email is required",variant:"destructive"});return}de(null),je(!0);try{await Ne(!1);const c=await he.mutateAsync({contract_id:d,doc_type:"contract",doc_number:x,client_name:r.client_name,client_email:r.client_email,signer_email:r.signer_email||"",snapshot_data:{formData:r,contractNumber:x}});await ge.mutateAsync(c.id),A({title:"✉️ Contract sent",description:`Contract ${x} sent via DocuSign`})}catch(c){c instanceof tt&&c.code==="consent_required"&&c.consentUrl?(de(c.consentUrl),A({title:"DocuSign Access Required",description:'Use the fixed "Grant DocuSign Access" button in the bottom-right corner.',variant:"destructive"})):A({title:"DocuSign Error",description:(c==null?void 0:c.message)||"Unknown error",variant:"destructive"})}finally{je(!1)}},[d,r,x,he,ge,Ne]),lt=v.useCallback(async()=>{if(d&&confirm("Delete this contract?"))try{await $.mutateAsync(d),A({title:"Contract deleted"}),J("list")}catch(c){A({title:"Error",description:c.message,variant:"destructive"})}},[d,$]),ot=c=>{const j=(o==null?void 0:o.get(c.id))||[],N=((P==null?void 0:P.get(c.id))||[]).some(h=>h.status==="completed"||h.status==="signed"),k=c.status==="cancelled"||c.status==="completed"?c.status:void 0;return Ee(j,N,k,c.payment_variant)};return i?e.jsx("div",{className:"flex items-center justify-center h-screen",children:e.jsx(me,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):t?!s&&!a?e.jsx(Qe,{to:"/production",replace:!0}):ve?e.jsx("div",{className:"min-h-screen bg-background p-6 print:p-0",children:e.jsx(Ze,{formData:r,contractNumber:x})}):e.jsx(Pt,{children:e.jsxs("div",{className:"print:hidden max-w-7xl mx-auto px-4 py-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[W==="editor"?e.jsx(q,{variant:"ghost",size:"icon",className:"rounded-xl h-8 w-8",onClick:()=>J("list"),children:e.jsx(Be,{className:"h-4 w-4"})}):e.jsx(qt,{to:"/production",children:e.jsx(q,{variant:"ghost",size:"icon",className:"rounded-xl h-8 w-8",children:e.jsx(Be,{className:"h-4 w-4"})})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:W==="editor"?d?`Contract ${x}`:"New Contract":"Contracts"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:W==="editor"?"Fill in client details and settings":"Client contract management"})]}),W==="list"&&e.jsxs(q,{onClick:$e,children:[e.jsx(We,{className:"w-4 h-4 mr-1.5"}),"New Contract"]})]}),it?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(me,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):rt?W==="list"?e.jsx("div",{className:"space-y-2",children:S.length===0?e.jsxs("div",{className:"text-center py-20 text-muted-foreground",children:[e.jsx(Ie,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{children:"No contracts yet"}),e.jsxs(q,{onClick:$e,variant:"outline",className:"mt-4",children:[e.jsx(We,{className:"w-4 h-4 mr-1.5"}),"Create first contract"]})]}):S.map(c=>e.jsxs("button",{onClick:()=>Re(c),className:"w-full flex items-center gap-4 p-4 rounded-xl ring-1 ring-border hover:bg-muted/40 transition-colors text-left",children:[e.jsx(Ie,{className:"w-5 h-5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:c.client_name}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[c.contract_number," · ",c.language.toUpperCase()]}),(()=>{const j=ot(c);return e.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${j.badgeClass}`,children:j.label})})(),(()=>{const g=((P==null?void 0:P.get(c.id))||[])[0];return g?g.status==="signed"?e.jsx(Se,{variant:"default",className:"bg-emerald-500/20 text-emerald-700 dark:text-emerald-400 ring-emerald-500/30 text-[10px] px-1.5 py-0",children:"Signed ✓"}):["sent","delivered"].includes(g.status)?e.jsx(Se,{variant:"destructive",className:"text-[10px] px-1.5 py-0",children:"Not Signed"}):null:null})()]})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(c.created_at).toLocaleDateString()}),e.jsx(Wt,{className:"w-4 h-4 text-muted-foreground"})]},c.id))}):e.jsxs(e.Fragment,{children:[be&&e.jsx("div",{className:"fixed bottom-6 right-6 z-50 max-w-[calc(100vw-3rem)] sm:max-w-md rounded-2xl border border-border bg-background shadow-lg ring-1 ring-border p-4 sm:p-5",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm text-foreground",children:"DocuSign access required"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Open DocuSign, approve access, then return here and send again."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{size:"sm",asChild:!0,children:e.jsxs("a",{href:be,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ue,{className:"w-4 h-4 mr-1.5"}),"Grant DocuSign Access"]})}),e.jsx(q,{size:"sm",variant:"outline",onClick:()=>de(null),children:"Close"})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"order-1 
14space-y-6",children:[(()=>{const c=Z.find(j=>j.doc_type==="contract");return c?c.status==="signed"?e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-xl bg-emerald-500/10 ring-1 ring-emerald-500/20 text-sm",children:[e.jsx(_e,{className:"w-4 h-4 text-emerald-600 dark:text-emerald-400 shrink-0"}),e.jsx("span",{className:"text-emerald-700 dark:text-emerald-300 font-medium",children:"Contract signed by all parties"})]}):["sent","delivered"].includes(c.status)?e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-xl bg-destructive/10 ring-1 ring-destructive/20 text-sm",children:[e.jsx(Ge,{className:"w-4 h-4 text-destructive shrink-0"}),e.jsx("span",{className:"text-destructive font-medium",children:"Contract sent but not yet signed by all parties"})]}):null:null})(),e.jsx(us,{data:r,onChange:L,onSaveDraft:()=>Ne(!1),onSaveAndPrint:()=>Ne(!0),onSendForSignature:dt,contractAlreadySent:Z.some(c=>c.doc_type==="contract"),onDelete:d?lt:void 0,saving:ie,sending:Me,isEdit:!!d,isAdmin:s,isSuperAdmin:n,allInvoicesPaid:R.length>0&&R.every(c=>c.paid),anyInvoicePaid:R.some(c=>c.paid),channels:b.map(c=>({id:c.id,name:c.name}))}),d&&R.length>0&&e.jsx(bs,{invoices:R,onTogglePaid:ct,loading:te.isPending,formData:r,contractNumber:x,canTogglePaid:s,documents:Z}),d&&Z.length>0&&e.jsx(js,{documents:Z,contractId:d})]}),e.jsx("div",{className:"order-2 rounded-xl ring-1 ring-border overflow-hidden max-h-[80vh] overflow-y-auto",children:e.jsx(Ze,{formData:r,contractNumber:x})})]})]}):e.jsx("div",{className:"text-center py-20 text-muted-foreground",children:e.jsx("p",{children:"No access. Manager role in a Production channel required."})})]})}):e.jsx(Qe,{to:"/auth",replace:!0})}export{wa 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.