/* global React, ReactDOM, qrcode */ // Agendamento · visual novo (C3). Mesmos dados de api.php; textos próprios em T2. const AG = window.AG; const { NOW, PAISES, BY_CODE } = AG; const qs0 = new URLSearchParams(location.search); AG.previa = /[?&]previa=1/.test(location.search); AG.novo = /novo\.html$/.test(location.pathname); const PRIV_HREF = AG.novo ? "novo.html?pg=privacidade" : "privacidade"; // ---------------------------------------------------------------- textos const T2 = { pt: { idioma: "Idioma", voltar: "VOLTAR", para: "para", com: "COM", local: "LOCAL", antec: "ANTECEDÊNCIA", antecV: (h) => "Até " + h + " h antes do horário", canc: "CANCELAMENTO", cancV: "Até 48 h antes, com devolução integral do Pix", cancVg: "Até 48 h antes, pelo link do e-mail", valorK: "VALOR", durK: "DURAÇÃO", escolhaDia: "Escolha do dia", semAnt: "Semana anterior", semProx: "Próxima semana", verMes: "VER O MÊS", fecharMesB: "FECHAR O MÊS", fecharMes: "Fechar o mês", escolhaHor: "ESCOLHA UM HORÁRIO", continuarCom: "CONTINUAR COM ", nome: "NOME", email: "E-MAIL", emailPh: "seu@email.com", tel: "TELEFONE (WHATSAPP)", pais: "País", telHint: "Fora do Brasil, escolha o país na lista. Se ele não estiver lá, escolha Outro e digite o número completo, começando com + e o código do país.", outroPais: "Outro +", cliente: "CLIENTE OU PROJETO", cliEsc: "Escolha o cliente ou projeto", tasksK: "TAREFAS PENDENTES · ", waSelf: "ENVIAR PARA MEU WHATSAPP", copiar: "COPIAR", copiado: "COPIADO ✓", copiaManual: "O navegador bloqueou a cópia. Toque no texto abaixo para selecionar e copie.", tasksHint: "Combinadas na última reunião. O ideal é chegar com elas feitas.", forms: "Formulários", abrir: "ABRIR", verificarF: "JÁ RESPONDI", feitoF: "RESPONDIDO ✓", naoAchei: "Ainda não encontrei a resposta. Pode levar alguns minutos.", marcarFeita: "MARCAR FEITA", feita: "FEITA ✓", bloqueado: "Para agendar, responda antes os formulários pendentes.", end: "ENDEREÇO DA REUNIÃO", endPh: "Rua, número, bairro, cidade", endHint: "Escola, clínica ou outro local onde a reunião vai acontecer.", mapa: "Ver no mapa", pauta: "PAUTA DA REUNIÃO", pautaPh: "O que você quer tratar", pautaHint: "Isso já entra como pauta da reunião. Use codinome para clientes.", matPrazo: "Vale só para este encontro. Dá para acrescentar ou tirar links até o começo da reunião.", matVazio: "Nenhum link enviado ainda.", matLink: "Link do material", matSalvando: "SALVANDO…", matSalvo: "Link guardado.", matSaiu: "Link retirado.", desfazer: "Desfazer", matCheio: "São 5 links, o limite. Tire um para acrescentar outro.", mat: "MATERIAIS PARA REVISÃO", matHint: "Links de vídeos, documentos ou pastas. Confira se estão compartilhados com admin@adrianobarboza.com. Para vídeos de clientes, use o Google Drive com acesso restrito. Até 5 links. Os links ficam guardados até 90 dias depois da reunião e então são apagados.", matDesc: "Descrição (ex.: vídeo da sessão de 02/10)", matAdd: "ADICIONAR LINK", remover: "Remover", eLinkPend: "Toque em Adicionar link ou apague o campo.", conv: "CONVIDAR MAIS PESSOAS", convHint: "Recebem o mesmo convite. Até 5 e-mails.", convAdd: "ADICIONAR", rep: "REPETIR ESTE HORÁRIO", freq: "FREQUÊNCIA", encontros: "ENCONTROS", freqs: { semanal: "Semanal", quinzenal: "Quinzenal", mensal: "Mensal" }, aceitar: "Aceitar", recusar: "Recusar", repOk: "confirmado", repSem: "sem horário, agendar depois", sug: (h) => "sugestão: " + h, ePend: "Aceite ou recuse as sugestões da repetição.", opcional: "opcional", de5: " de 5", wpp: "Receber a confirmação e os lembretes também por WhatsApp.", lembrar: "Lembrar meus dados neste aparelho para a próxima vez.", lgpd1: "Concordo com o uso destes dados apenas para organizar a reunião, conforme a ", lgpdLink: "Política de Privacidade", lgpd2: ". Por favor, não envie aqui informações de saúde ou dados de crianças. Os dados ficam guardados até 90 dias depois da reunião.", seuHor: "SEU HORÁRIO", as: "às", min: "minutos", valor: "Valor", trocar: "TROCAR HORÁRIO", confirmar: "CONFIRMAR AGENDAMENTO", reservar: "RESERVAR E IR PARA O PAGAMENTO", enviando: "ENVIANDO…", eNome: "Informe o seu nome.", eEmail: "Informe um e-mail válido.", eTel: "Informe o telefone completo.", ePauta: "Conte em poucas palavras o que quer tratar.", eCli: "Escolha o cliente da reunião.", eEnd: "Informe o endereço da reunião.", eLgpd: "Confirme para continuar.", eUrl: "Use um link completo, começando com https://", eConv: "E-mail inválido.", payLead: "Seu horário fica reservado enquanto você paga por Pix.", pagar: "JÁ PAGUEI", recebedor: "No app do banco, o recebedor aparece como Aurea Saúde Comportamental LTDA, a empresa do Adriano.", aguardK: "HORÁRIO RESERVADO · PIX EM CONFERÊNCIA", aguardTxt: "Assim que eu conferir o Pix, a confirmação chega no seu e-mail.", comprov: "Enviar comprovante por e-mail", pixQr: "No app do banco, escolha Pix e aponte a câmera para o código.", pixQrAria: "QR code do Pix", pixCc: "PIX COPIA E COLA", copiarPix: "COPIAR CÓDIGO", pixCopiado: "CÓDIGO COPIADO ✓", pixNota: "Eu confiro o pagamento e confirmo por e-mail. Se o prazo acabar sem pagamento, o horário volta a ficar livre.", reservaAte: (x) => "Reserva válida até " + x + ".", idPix: "Identificador", expirouK: "PRAZO ENCERRADO", expirou: "O prazo para o pagamento acabou e o horário foi liberado.", novoHor: "ESCOLHER OUTRO HORÁRIO", fusoK: "HORÁRIOS EM", brasilia: "Horário de Brasília", seuFuso: (z) => "Seu fuso (" + z + ")", fusoNota: (x) => "Em Brasília: " + x, emMcz: " em Brasília", semVagaSem: "Sem horários livres nestas datas.", irPara: "IR PARA ", semVaga: "Não há horários livres nas próximas semanas.", lotado: "Este dia está lotado.", avise: "ME AVISE SE ABRIR VAGA", avisado: "Combinado. Aviso por e-mail se abrir vaga.", voltaOi: (n) => "Que bom ver você de novo, " + n + ".", voltaTxt: "Preenchi com os dados da última vez, guardados só neste aparelho.", naoSou: "NÃO SOU EU", altK: "ALTERAR AGENDAMENTO", atualK: "SEU HORÁRIO ATUAL", altLead: "Escolha abaixo o novo horário. O atual continua valendo até você confirmar a troca.", cancelarAg: "CANCELAR AGENDAMENTO", cancPerg: (x) => "Cancelar o horário de " + x + "?", cancRegra: "Até 48 h antes, sem custo. Se houve pagamento, o Pix é devolvido integralmente.", cancOk: "CONFIRMAR CANCELAMENTO", manter: "MANTER HORÁRIO", trocarPara: "TROCAR PARA ", alteradoK: "AGENDAMENTO ALTERADO", antes: "Antes: ", canceladoK: "AGENDAMENTO CANCELADO", cancLead: "O horário foi liberado e você recebe a confirmação por e-mail.", devolucao: "O Pix pago será devolvido integralmente para a conta de origem em até 2 dias úteis.", semPrazo: "Faltam menos de 48 h. Para cancelar ou remarcar, escreva para admin@adrianobarboza.com.", inativo: "Este agendamento não está mais ativo.", disp: "disponível", indisp: "sem horário", lotadoA: "lotado", liveDia: (x) => "Dia escolhido: " + x, mesAnt: "Mês anterior", mesProx: "Próximo mês", verTxt: (m) => "As tarefas deste cliente são protegidas. Para vê-las, confirme que é você: envio um código para " + m + ", o e-mail cadastrado.", verEnviar: "ENVIAR CÓDIGO", verCodeL: "Código de 6 números", verOk: "CONFIRMAR", verReenviar: "Reenviar código", eCode: "O código tem 6 números.", verNota: "O código vale por 10 minutos.", verEnviado: (m) => "Enviei o código para " + m + ".", diaEscolhido: "DIA ESCOLHIDO", nenhumDia: "Nenhum dia ainda", cancelar: "CANCELAR", confirmarDia: "CONFIRMAR", confirmadoK: "AGENDAMENTO CONFIRMADO", part: "PARTICIPANTES", ateLa: "Até lá!", e_: " e ", convidado: (n) => n === 1 ? "1 convidado" : n + " convidados", dur: "DURAÇÃO", cardAria: "Cartão de confirmação", obrigado: (n) => "Obrigado, " + n + ".", fimRep: (n) => "Ao todo, " + n + " encontros, na repetição escolhida.", fimConv: "O convite chega no seu e-mail.", fimAviso1: "Se não aparecer em alguns minutos, olhe o spam ou escreva para admin@adrianobarboza.com.", fimAviso2: "Para cancelar ou remarcar, use o link do e-mail de confirmação, até 48 h antes do horário.", addCal: "ADICIONAR À AGENDA", gcal: "Google Agenda", outro: "AGENDAR OUTRO HORÁRIO", etapasAria: "Etapas do agendamento", e3: ["HORÁRIO", "DADOS", "CONFIRMAÇÃO"], e4: ["HORÁRIO", "DADOS", "PAGAMENTO", "CONFIRMAÇÃO"], eAlt: ["NOVO HORÁRIO", "CONFIRMAÇÃO"], kick: "AGENDAMENTO", kickP: "LINK PESSOAL", kickPres: "PRESENCIAL", kickPago: "PAGO", sala: { meet: "Online, Google Meet", zoom: "Online, Zoom", presencial: "Presencial" }, presPessoa: "Presencial, no endereço informado", wk: ["DOM", "SEG", "TER", "QUA", "QUI", "SEX", "SÁB"], wkL: ["domingo", "segunda-feira", "terça-feira", "quarta-feira", "quinta-feira", "sexta-feira", "sábado"], meses: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"], diaL: (d, T) => T.wkL[d.getDay()] + ", " + d.getDate() + " de " + T.meses[d.getMonth()], diaC: (d, T) => T.wk[d.getDay()].toLowerCase() + ", " + d.getDate(), pend: (n) => n === 1 ? "1 campo precisa de atenção." : n + " campos precisam de atenção.", remove: (x) => "Remover " + x, carregando: "CARREGANDO…", invTit: "POR CONVITE", invLead: "Os horários abrem pelo link que você recebeu.", invTxt: "Cada tipo de encontro tem o seu endereço, com duração, formato e horários próprios. Se você ainda não recebeu o seu, escreva para ", conhecer: "CONHECER O TRABALHO", falar: "FALAR COMIGO", lgpdFoot: "Dados tratados conforme a LGPD (Lei nº 13.709/2018)", pubTitA: "AGENDE UMA", pubTitB: "CONVERSA", pubLead: "Para começar, marque uma conversa inicial.", pubTxt: "Supervisão, consultoria, palestras e cursos abrem por convite, cada um com o seu link. Se você já recebeu o seu, use o endereço do e-mail.", aberto: "ABERTO PARA AGENDAR", abertoAria: "Encontros abertos", fmtK: "FORMATO", gratuita: ", gratuita", verHor: "VER HORÁRIOS", semConv: "Ainda sem convite para outro encontro? ", indisponivel: "Link indisponível", listaTit: "AGENDE UMA CONVERSA", listaVazia: "Os horários abrem pelo link que você recebeu. Se ainda não recebeu o seu, escreva para ", previa: "PRÉVIA DO RASCUNHO · NADA É GRAVADO NEM ENVIADO", erroRede: "Não consegui falar com o servidor. Tente de novo." }, en: { idioma: "Language", voltar: "BACK", para: "for", com: "WITH", local: "WHERE", antec: "NOTICE", antecV: (h) => "Up to " + h + " h before the time", canc: "CANCELLATION", cancV: "Up to 48 h before, with a full Pix refund", cancVg: "Up to 48 h before, via the e-mail link", valorK: "FEE", durK: "LENGTH", escolhaDia: "Choose a day", semAnt: "Previous week", semProx: "Next week", verMes: "SEE THE MONTH", fecharMesB: "CLOSE THE MONTH", fecharMes: "Close the month", escolhaHor: "CHOOSE A TIME", continuarCom: "CONTINUE WITH ", nome: "NAME", email: "E-MAIL", emailPh: "you@email.com", tel: "PHONE (WHATSAPP)", pais: "Country", telHint: "Outside Brazil, pick your country from the list. If it is not there, choose Other and type the full number, starting with + and the country code.", outroPais: "Other +", cliente: "CLIENT OR PROJECT", cliEsc: "Choose the client or project", tasksK: "PENDING TASKS · ", waSelf: "SEND TO MY WHATSAPP", copiar: "COPY", copiado: "COPIED ✓", copiaManual: "Your browser blocked copying. Tap the text below to select it and copy.", tasksHint: "Agreed at the last meeting. Ideally, come with them done.", forms: "Forms", abrir: "OPEN", verificarF: "I HAVE ANSWERED", feitoF: "ANSWERED ✓", naoAchei: "I could not find the answer yet. It can take a few minutes.", marcarFeita: "MARK DONE", feita: "DONE ✓", bloqueado: "To book, please answer the pending forms first.", end: "MEETING ADDRESS", endPh: "Street, number, neighbourhood, city", endHint: "School, clinic or other place where the meeting will happen.", mapa: "See on the map", pauta: "MEETING AGENDA", pautaPh: "What you would like to discuss", pautaHint: "This becomes the meeting agenda. Use codenames for clients.", matPrazo: "For this meeting only. You can add or remove links until the meeting starts.", matVazio: "No links sent yet.", matLink: "Material link", matSalvando: "SAVING…", matSalvo: "Link saved.", matSaiu: "Link removed.", desfazer: "Undo", matCheio: "You have 5 links, the limit. Remove one to add another.", mat: "MATERIALS FOR REVIEW", matHint: "Links to videos, documents or folders. Make sure they are shared with admin@adrianobarboza.com. For client videos, use Google Drive with restricted access. Up to 5 links. Links are kept for up to 90 days after the meeting and then deleted.", matDesc: "Description (e.g. session video from Oct 2)", matAdd: "ADD LINK", remover: "Remove", eLinkPend: "Tap Add link or clear the field.", conv: "INVITE MORE PEOPLE", convHint: "They receive the same invitation. Up to 5 e-mails.", convAdd: "ADD", rep: "REPEAT THIS TIME", freq: "FREQUENCY", encontros: "SESSIONS", freqs: { semanal: "Weekly", quinzenal: "Every two weeks", mensal: "Monthly" }, aceitar: "Accept", recusar: "Decline", repOk: "confirmed", repSem: "no time, book later", sug: (h) => "suggestion: " + h, ePend: "Accept or decline the suggested times.", opcional: "optional", de5: " of 5", wpp: "Also receive the confirmation and reminders on WhatsApp.", lembrar: "Remember my details on this device for next time.", lgpd1: "I agree to the use of this data only to organise the meeting, under the ", lgpdLink: "Privacy Policy", lgpd2: ". Please do not send health information or data about children here. Data is kept for up to 90 days after the meeting.", seuHor: "YOUR TIME", as: "at", min: "minutes", valor: "Fee", trocar: "CHANGE TIME", confirmar: "CONFIRM BOOKING", reservar: "RESERVE AND GO TO PAYMENT", enviando: "SENDING…", eNome: "Please enter your name.", eEmail: "Please enter a valid e-mail.", eTel: "Please enter the full phone number.", ePauta: "Tell me briefly what you would like to discuss.", eCli: "Choose the client for this meeting.", eEnd: "Please enter the meeting address.", eLgpd: "Please confirm to continue.", eUrl: "Use a full link, starting with https://", eConv: "Invalid e-mail.", payLead: "Your time is held while you pay by Pix.", pagar: "I HAVE PAID", recebedor: "In your banking app, the payee shows as Aurea Saúde Comportamental LTDA, Adriano’s company.", aguardK: "TIME RESERVED · PIX BEING CHECKED", aguardTxt: "As soon as I check the Pix, the confirmation arrives in your e-mail.", comprov: "Send the receipt by e-mail", pixQr: "In your banking app, choose Pix and point the camera at the code.", pixQrAria: "Pix QR code", pixCc: "PIX COPY AND PASTE", copiarPix: "COPY CODE", pixCopiado: "CODE COPIED ✓", pixNota: "I check the payment and confirm by e-mail. If the hold expires without payment, the time becomes free again.", reservaAte: (x) => "Hold valid until " + x + ".", idPix: "Reference", expirouK: "HOLD EXPIRED", expirou: "The payment window ended and the time was released.", novoHor: "PICK ANOTHER TIME", fusoK: "TIMES IN", brasilia: "Brasília time", seuFuso: (z) => "Your time zone (" + z + ")", fusoNota: (x) => "Brasília time: " + x, emMcz: " Brasília time", semVagaSem: "No free times on these dates.", irPara: "GO TO ", semVaga: "There are no free times in the coming weeks.", lotado: "This day is fully booked.", avise: "TELL ME IF A SLOT OPENS", avisado: "Done. I will e-mail you if a slot opens.", voltaOi: (n) => "Good to see you again, " + n + ".", voltaTxt: "I filled in your details from last time, stored only on this device.", naoSou: "NOT ME", altK: "CHANGE BOOKING", atualK: "YOUR CURRENT TIME", altLead: "Choose the new time below. The current one stays valid until you confirm the change.", cancelarAg: "CANCEL BOOKING", cancPerg: (x) => "Cancel your time on " + x + "?", cancRegra: "Free of charge up to 48 h before. If you paid, the Pix is refunded in full.", cancOk: "CONFIRM CANCELLATION", manter: "KEEP MY TIME", trocarPara: "CHANGE TO ", alteradoK: "BOOKING CHANGED", antes: "Before: ", canceladoK: "BOOKING CANCELLED", cancLead: "The time is free again and you will get a confirmation by e-mail.", devolucao: "The Pix you paid will be refunded in full to the account it came from, within 2 business days.", semPrazo: "Less than 48 h left. To cancel or reschedule, write to admin@adrianobarboza.com.", inativo: "This booking is no longer active.", disp: "available", indisp: "no times", lotadoA: "fully booked", liveDia: (x) => "Selected day: " + x, mesAnt: "Previous month", mesProx: "Next month", verTxt: (m) => "The tasks for this client are protected. To see them, confirm it is you: I will send a code to " + m + ", the registered e-mail.", verEnviar: "SEND CODE", verCodeL: "6-digit code", verOk: "CONFIRM", verReenviar: "Resend code", eCode: "The code has 6 digits.", verNota: "The code is valid for 10 minutes.", verEnviado: (m) => "I sent the code to " + m + ".", diaEscolhido: "SELECTED DAY", nenhumDia: "No day yet", cancelar: "CANCEL", confirmarDia: "CONFIRM", confirmadoK: "BOOKING CONFIRMED", part: "PARTICIPANTS", ateLa: "See you then!", e_: " and ", convidado: (n) => n === 1 ? "1 guest" : n + " guests", dur: "LENGTH", cardAria: "Confirmation card", obrigado: (n) => "Thank you, " + n + ".", fimRep: (n) => n + " sessions in total, following the repetition you chose.", fimConv: "The invitation is on its way to your e-mail.", fimAviso1: "If it does not arrive within a few minutes, check your spam folder or write to admin@adrianobarboza.com.", fimAviso2: "To cancel or reschedule, use the link in the confirmation e-mail, up to 48 h before the time.", addCal: "ADD TO CALENDAR", gcal: "Google Calendar", outro: "BOOK ANOTHER TIME", etapasAria: "Booking steps", e3: ["TIME", "DETAILS", "CONFIRMATION"], e4: ["TIME", "DETAILS", "PAYMENT", "CONFIRMATION"], eAlt: ["NEW TIME", "CONFIRMATION"], kick: "BOOKING", kickP: "PERSONAL LINK", kickPres: "IN PERSON", kickPago: "PAID", sala: { meet: "Online, Google Meet", zoom: "Online, Zoom", presencial: "In person" }, presPessoa: "In person, at the address given", wk: ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"], wkL: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], meses: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], diaL: (d, T) => T.wkL[d.getDay()] + ", " + T.meses[d.getMonth()] + " " + d.getDate(), diaC: (d, T) => T.wk[d.getDay()].slice(0, 1) + T.wk[d.getDay()].slice(1).toLowerCase() + " " + d.getDate(), pend: (n) => n === 1 ? "1 field needs attention." : n + " fields need attention.", remove: (x) => "Remove " + x, carregando: "LOADING…", invTit: "BY INVITATION", invLead: "Times open through the link you received.", invTxt: "Each kind of meeting has its own address, with its own length, format and times. If you have not received yours yet, write to ", conhecer: "ABOUT MY WORK", falar: "CONTACT ME", lgpdFoot: "Data handled under Brazil’s LGPD (Law no. 13,709/2018)", pubTitA: "BOOK A", pubTitB: "CONVERSATION", pubLead: "To begin, book an initial conversation.", pubTxt: "Supervision, consulting, talks and courses open by invitation, each with its own link. If you already have yours, use the address in the e-mail.", aberto: "OPEN FOR BOOKING", abertoAria: "Open meetings", fmtK: "FORMAT", gratuita: ", free", verHor: "SEE TIMES", semConv: "No invitation for another meeting yet? ", indisponivel: "Link not available", listaTit: "BOOK A MEETING", listaVazia: "Times open through the link you received. If you have not received yours yet, write to ", previa: "DRAFT PREVIEW · NOTHING IS SAVED OR SENT", erroRede: "I could not reach the server. Please try again." }, }; // ---------------------------------------------------------------- API (prévia simulada dentro do painel) function agPrevHorarios(l, de, ate) { const out = { dias: {}, cheios: [] }, min = Date.now() + (+l.antecedencia || 0) * 36e5, max = Date.now() + (+l.janela || 90) * 864e5, dur = +l.dur || 60, passo = +l.passo || 30; for (let d = new Date(de + "T00:00:00"); AG.ymd(d) <= ate; d.setDate(d.getDate() + 1)) { const livres = []; ((l.horarios || {})[String(d.getDay())] || []).forEach(([a, b]) => { const am = +a.slice(0, 2) * 60 + +a.slice(3, 5), bm = +b.slice(0, 2) * 60 + +b.slice(3, 5); for (let t = am; t + dur <= bm; t += passo) { const ts = new Date(d.getFullYear(), d.getMonth(), d.getDate(), Math.floor(t / 60), t % 60); if (ts >= min && ts <= max) livres.push(AG.pad(Math.floor(t / 60)) + ":" + AG.pad(t % 60)); } }); if (livres.length) out.dias[AG.ymd(d)] = livres; } return out; } async function agMock(acao, params, body) { const l = AG.prevLink || {}; await new Promise((ok) => setTimeout(ok, 150)); if (acao === "horarios") return agPrevHorarios(l, params.de, params.ate); if (acao === "reservar") { const total = (+l.preco || 0) * Math.max(1, (body.horarios || []).length), pix = total > 0 && l.exigirPix !== false; return { ok: true, status: pix ? "aguardando_pix" : "confirmado", token: "previa", credito: 0, pix: pix ? { codigo: "PREVIA-NADA-E-COBRADO-" + total.toFixed(2), valor: total, txid: "PREVIA", expira: Math.floor(Date.now() / 1000) + 86400 } : null }; } if (acao === "verificar_form") return { feito: false }; return { ok: true }; } const agApiReal = async (acao, params, body) => { let r; try { r = await fetch("api.php?acao=" + acao + (params ? "&" + new URLSearchParams(params) : ""), body ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : undefined); } catch (e) { throw Object.assign(new Error(T2[AG.lang || "pt"].erroRede), { code: 0 }); } const j = await r.json().catch(() => ({})); if (!r.ok) throw Object.assign(new Error(j.erro || "Erro " + r.status), { code: r.status }); return j; }; const agApi = (acao, params, body) => AG.previa ? agMock(acao, params, body) : agApiReal(acao, params, body); const agQr = (s) => { try { const q = qrcode(0, "M"); q.addData(s); q.make(); return q.createSvgTag({ cellSize: 4, margin: 0, scalable: true }); } catch (e) { return ""; } }; const store = { get(k) { try { return JSON.parse(localStorage.getItem(k) || "null"); } catch (e) { return null; } }, set(k, v) { try { v == null ? localStorage.removeItem(k) : localStorage.setItem(k, JSON.stringify(v)); } catch (e) {} } }; const sstore = { get(k) { try { return sessionStorage.getItem(k) || ""; } catch (e) { return ""; } }, set(k, v) { try { v ? sessionStorage.setItem(k, v) : sessionStorage.removeItem(k); } catch (e) {} } }; const copyText = async (txt) => { try { await navigator.clipboard.writeText(txt); return true; } catch (e) { return false; } }; const addDays = (d, n) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n); const dayOnly = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()); const brl = (v) => "R$ " + Number(v).toFixed(2).replace(".", ","); const URL_OK = (u) => /^https:\/\/\S+\.\S+/.test(String(u).trim()); const MAIL_OK = (e) => /^\S+@\S+\.\S+$/.test(String(e).trim()); const LOCAL_TZ = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || "America/Sao_Paulo"; } catch (e) { return "America/Sao_Paulo"; } })(); const LOCAL_IS_BRT = AG.sameAsBRT(LOCAL_TZ); const agLang0 = () => { const q = qs0.get("lang"); if (q === "en" || q === "pt") return q; try { const g = sessionStorage.getItem("ag-lang"); if (g === "en" || g === "pt") return g; } catch (e) { /* sem armazenamento */ } return "pt"; }; // carrega os horários de um mês (uma vez) function loadMonth(d, extra, done) { const a = new Date(d.getFullYear(), d.getMonth(), 1), b = new Date(d.getFullYear(), d.getMonth() + 1, 0), k = AG.ymd(a); if (AG.carregados[k]) return; AG.carregados[k] = 1; agApi("horarios", { l: AG.slug, de: AG.ymd(a), ate: AG.ymd(b), ...(extra || {}) }) .then((j) => { Object.assign(AG.AVAIL.dias, j.dias || {}); AG.AVAIL.cheios = AG.AVAIL.cheios.concat(j.cheios || []); AG.mesesOk[k] = 1; done(); if (AG.onUpdate) AG.onUpdate(); }) .catch(() => { AG.carregados[k] = 0; done(); }); } AG.mesesOk = {}; // ---------------------------------------------------------------- moldura const SYM = [["246.2,78.9 498.2,229.1 437.7,330.6 185.7,180.4", -8.5, -15.9, 0], ["78.9,246.2 180.4,185.7 330.6,437.7 229.1,498.2", -15.9, -8.5, -.4], ["819.6,185.7 921.1,246.2 770.9,498.2 669.4,437.7", 15.9, -8.5, -.8], ["501.8,229.1 753.8,78.9 814.3,180.4 562.3,330.6", 8.5, -15.9, -1.2], ["562.3,669.4 814.3,819.6 753.8,921.1 501.8,770.9", 8.5, 15.9, 0], ["669.4,562.3 770.9,501.8 921.1,753.8 819.6,814.3", 15.9, 8.5, -.4], ["229.1,501.8 330.6,562.3 180.4,814.3 78.9,753.8", -15.9, 8.5, -.8], ["185.7,819.6 437.7,669.4 498.2,770.9 246.2,921.1", -8.5, 15.9, -1.2], ["500.0,0.1 589.9,90.0 500.0,179.9 410.1,90.0", 0, -18, 0], ["910.0,410.1 999.9,500.0 910.0,589.9 820.1,500.0", 18, 0, -.4], ["410.1,910.0 500.0,820.1 589.9,910.0 500.0,999.9", 0, 18, -.8], ["90.0,410.1 179.9,500.0 90.0,589.9 0.1,500.0", -18, 0, -1.2], ["500.0,293.0 707.0,500.0 500.0,707.0 293.0,500.0", 0, 0, 0]]; function Symbol({ cls, anim }) { return ; } function Frame({ lang, setLang, steps, children, noSym, foot }) { const T = T2[lang]; React.useEffect(() => { document.documentElement.lang = lang === "en" ? "en" : "pt-BR"; AG.lang = lang; }, [lang]); return (
{noSym ? null : }
ADRIANO BARBOZA
{["pt", "en"].map((l) => )}
{AG.previa ?

{T.previa}

: null}
{children}
{steps ? ( ) : null} {foot ? : null}
); } // ---------------------------------------------------------------- fuso function useZone(lang) { const [tz, setTz] = React.useState("brt"); const locale = lang === "en" ? "en-GB" : "pt-BR"; const local = tz === "local" && !LOCAL_IS_BRT; const label = (day, s) => { if (!local) return { main: AG.fmtHora(s), brt: null, shift: 0 }; const z = AG.inZone(day, s, LOCAL_TZ, locale); return { main: z.hm, brt: AG.fmtHora(s), shift: z.shift }; }; return { tz, setTz, label, local, tzName: LOCAL_TZ.replace(/_/g, " ") }; } // ---------------------------------------------------------------- escolha do dia e horário function Picker({ T, lang, zone, dur, day, setDay, slot, setSlot, onGo, goLabel, espera, setEspera, f, setF, locked }) { const [, setTick] = React.useState(0); const bump = () => setTick((x) => x + 1); const today = dayOnly(NOW); const lim = AG.limite ? dayOnly(AG.limite) : addDays(today, 90); const weekStart = (d) => addDays(d, -d.getDay()); const [start, setStart] = React.useState(() => weekStart(day || today)); const [open, setOpen] = React.useState(false); const [mon, setMon] = React.useState(() => new Date((day || today).getFullYear(), (day || today).getMonth(), 1)); const [pend, setPend] = React.useState(null); const [live, setLive] = React.useState(""); const [wait, setWait] = React.useState({ open: false, busy: false, err: "" }); const isMob = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(max-width:900px)").matches; const nDays = isMob ? 7 : 14; const extra = AG.o ? { o: AG.o } : {}; const ensure = (d) => loadMonth(d, extra, bump); React.useEffect(() => { ensure(start); ensure(addDays(start, nDays - 1)); }, [start, nDays]); React.useEffect(() => { if (open) ensure(mon); }, [open, mon]); React.useEffect(() => { if (day) { const ws = weekStart(day); if (day < start || day > addDays(start, nDays - 1)) setStart(ws); } }, [day && day.getTime()]); const slotsOf = (d) => AG.slotsFor(d); const fullOf = (d) => AG.isFull(d); const dayState = (d) => d < today || d > lim ? "off" : slotsOf(d).length ? "av" : fullOf(d) ? "full" : "off"; const strip = Array.from({ length: nDays }, (_, i) => addDays(start, i)); const stripAv = strip.some((d) => dayState(d) === "av"); const stripFull = strip.find((d) => dayState(d) === "full"); const loadedThrough = (() => { let d = new Date(today.getFullYear(), today.getMonth(), 1); while (AG.mesesOk[AG.ymd(d)] && d <= lim) d = new Date(d.getFullYear(), d.getMonth() + 1, 1); return d; })(); const stripEnd = addDays(start, nDays - 1); const nextFree = Object.keys(AG.AVAIL.dias).filter((k) => AG.AVAIL.dias[k].length && k > AG.ymd(stripEnd)).sort()[0]; React.useEffect(() => { if (!stripAv && !nextFree && loadedThrough <= lim) ensure(loadedThrough); }); const allEmpty = !stripAv && !nextFree && loadedThrough > lim; const pick = (d) => { setDay(d); setSlot(null); setLive(T.liveDia(T.diaL(d, T))); }; const key = (d) => (ev) => { const k = ev.key; let tgt = null; if (k === "ArrowRight") tgt = addDays(d, 1); else if (k === "ArrowLeft") tgt = addDays(d, -1); else if (k === "ArrowDown") tgt = addDays(d, 7); else if (k === "ArrowUp") tgt = addDays(d, -7); if (!tgt) return; ev.preventDefault(); for (let i = 0; i < 60 && tgt >= today && tgt <= lim; i++) { if (dayState(tgt) !== "off") break; tgt = addDays(tgt, k === "ArrowLeft" || k === "ArrowUp" ? -1 : 1); } if (tgt < today || tgt > lim || dayState(tgt) === "off") return; pick(tgt); setTimeout(() => { const el = document.querySelector('[data-day="' + AG.ymd(tgt) + '"]'); if (el) el.focus(); }, 30); }; const canPrev = start > weekStart(today), canNext = addDays(start, nDays) <= lim; const mHdr = (() => { const a = start, b = stripEnd; const m = (d) => T.meses[d.getMonth()].toUpperCase(); return a.getMonth() === b.getMonth() ? m(a) + " " + a.getFullYear() : m(a) + " · " + m(b) + " " + b.getFullYear(); })(); const slots = day ? slotsOf(day) : []; const selFull = day && dayState(day) === "full"; // mês const first = mon, nDm = new Date(mon.getFullYear(), mon.getMonth() + 1, 0).getDate(); const cells = []; for (let i = 0; i < first.getDay(); i++) cells.push(null); for (let i = 1; i <= nDm; i++) cells.push(new Date(mon.getFullYear(), mon.getMonth(), i)); const monPrev = mon > new Date(today.getFullYear(), today.getMonth(), 1), monNext = new Date(mon.getFullYear(), mon.getMonth() + 1, 1) <= lim; const openCal = () => { setPend(day); setMon(new Date((day || start).getFullYear(), (day || start).getMonth(), 1)); setOpen(true); }; const closeCal = () => setOpen(false); React.useEffect(() => { if (!open) return; const h = (e) => { if (e.key === "Escape") closeCal(); }; window.addEventListener("keydown", h); return () => window.removeEventListener("keydown", h); }, [open]); const pedirAviso = async (d) => { if (!f.nome.trim() || !MAIL_OK(f.email)) { setWait({ ...wait, open: true, err: !f.nome.trim() ? T.eNome : T.eEmail }); return; } setWait({ ...wait, busy: true, err: "" }); try { await agApi("espera", null, { slug: AG.slug, dia: AG.ymd(d), nome: f.nome, email: f.email, lang }); setEspera(AG.ymd(d)); setWait({ open: false, busy: false, err: "" }); } catch (e) { setWait({ open: true, busy: false, err: e.message }); } }; const waitBox = (d) => espera === AG.ymd(d) ? {T.avisado} : wait.open ? (
setF({ ...f, nome: e.target.value })} /> setF({ ...f, email: e.target.value })} /> {wait.err ? {wait.err} : null}
) : ; return (

{mHdr}

{!LOCAL_IS_BRT ? ( ) : null}
{strip.map((d) => { const st = dayState(d), sel = AG.sameDay(d, day); const lab = T.diaL(d, T) + ", " + (st === "av" ? T.disp : st === "full" ? T.lotadoA : T.indisp); if (st === "off") return {T.wk[d.getDay()]}{d.getDate()}; return ; })}
{locked ? null : day && slots.length ? (
{T.diaC(day, T)} {slots.map((s) => { const z = zone.label(day, s), on = slot && slot.h === s.h && slot.m === s.m; return ; })} {slot ? : {T.escolhaHor}}
) : selFull ? (
{T.lotado}{waitBox(day)}
) : allEmpty ? (
{T.semVaga}{waitBox(stripFull || start)}
) : !stripAv && nextFree ? (
{T.semVagaSem}
) : null}

{live}

{open ? (

{T.meses[mon.getMonth()]}

{mon.getFullYear()}
{T.wk.map((w) => {w})}
{cells.map((d, i) => { if (!d) return ; const st = dayState(d); if (st === "off") return {d.getDate()}; return ; })}
{T.diaEscolhido} {pend ? T.diaL(pend, T) : T.nenhumDia}
) : null}
); } // ---------------------------------------------------------------- tarefas do link pessoal (com código) function TasksBox({ T, lang, ps, setPs }) { const [st, setSt] = React.useState({ sent: false, code: "", err: "", busy: false, msg: "", copied: false, copyFail: false, miss: {} }); const up = (x) => setSt((o) => ({ ...o, ...x })); const tit = T.tasksK + ps.projeto; const send = async () => { up({ busy: true, err: "" }); try { const j = await agApi("enviar_codigo", null, { slug: AG.slug, p: AG.p, lang }); up({ sent: true, busy: false, msg: T.verEnviado(j.para || ps.emailMascara) }); } catch (e) { up({ busy: false, err: e.message }); } }; const ok = async () => { if (!/^\d{6}$/.test(st.code)) { up({ err: T.eCode }); return; } up({ busy: true, err: "" }); try { const j = await agApi("verificar_codigo", null, { slug: AG.slug, p: AG.p, codigo: st.code }); sstore.set("ag-v-" + AG.slug + "-" + AG.p, j.v); AG.v = j.v; setPs({ ...ps, verificado: true, formularios: j.formularios || [], tarefas: j.tarefas || [] }); } catch (e) { up({ busy: false, err: e.message }); } }; if (!ps.verificado) return (
{tit}

{T.verTxt(ps.emailMascara)}

{!st.sent ? : ( {st.msg}
up({ code: e.target.value.replace(/\D/g, "").slice(0, 6), err: "" })} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); ok(); } }} aria-label={T.verCodeL} aria-invalid={!!st.err} placeholder="000000" />
{T.verNota}
)} {st.err ? {st.err} : null}
); const forms = ps.formularios || [], tasks = ps.tarefas || []; const txt = tasks.map((t) => "• " + t.titulo + (t.prazo ? " (" + t.prazo + ")" : "")).concat(forms.filter((x) => !x.feito).map((x) => "• " + x.titulo + ": " + x.url)).join("\n"); const check = async (id) => { try { const j = await agApi("verificar_form", null, { slug: AG.slug, p: AG.p, id, v: AG.v }); if (j.feito) setPs({ ...ps, formularios: forms.map((x) => x.id === id ? { ...x, feito: true } : x) }); else up({ miss: { ...st.miss, [id]: true } }); } catch (e) { up({ miss: { ...st.miss, [id]: true } }); } }; const togTask = (t) => { const v = !t.feita; setPs({ ...ps, tarefas: tasks.map((x) => x.id === t.id ? { ...x, feita: v } : x) }); agApi("tarefa_feita", null, { slug: AG.slug, p: AG.p, id: t.id, feita: v, v: AG.v }).catch(() => {}); }; if (!forms.length && !tasks.length) return null; return (
{tit} {forms.length ? : null} {tasks.length ? : null}
{T.waSelf}
{st.copyFail ? {T.copiaManual}