<?php
/**
 * Pagina "Programare consultație"
 * Flux de booking în 3 pași (calendar → formular → confirmare).
 * Implementare pe baza design-ului "Legal Consultation Booking" (Claude Design bundle).
 * Headerul/limba sunt gestionate de site; aplicația React e doar pentru conținut.
 */
?>
<!-- Fonturi specifice design-ului booking (Fraunces, Instrument Serif, JetBrains Mono) -->
<link href="https://fonts.googleapis.com/css2?family=Fraunces:ital,wght@0,400;0,500;0,600;1,400;1,500&family=Instrument+Serif:ital@0;1&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">

<style>
/* Forțăm headerul întunecat pe această pagină (fundal ivoriu face textul alb invizibil
   pe varianta transparentă — reproducem look-ul din `.header-scrolled` de pe home). */
body .header {
    background: rgba(26, 35, 50, 0.97);
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
    box-shadow: 0 2px 20px rgba(0,0,0,0.15);
}

/* ===================================================================
 *  Booking page — editorial theme (scope: .booking-root)
 * =================================================================== */
.booking-root {
    --ed-bg: #f3efe6;
    --ed-paper: #fbf8f1;
    --ed-ink: #1a2332;
    --ed-ink-2: #2b3547;
    --ed-muted: #6b6e6a;
    --ed-rule: #d9d3c4;
    --ed-gold: #a07a2a;
    --ed-gold-soft: #c9a659;

    padding-top: var(--header-height);
    background: var(--ed-bg);
    color: var(--ed-ink);
    font-family: 'Inter', system-ui, sans-serif;
    min-height: 100vh;
}
.booking-root * { box-sizing: border-box; }
.booking-root button { font-family: inherit; cursor: pointer; border: none; background: none; color: inherit; }
.booking-root button:disabled { cursor: not-allowed; }

/* Top strip cu stepper */
.booking-root .booking-topstrip {
    display: flex; justify-content: flex-end; align-items: center;
    padding: 22px 56px 0;
    background: var(--ed-paper);
    border-bottom: 1px solid var(--ed-rule);
    padding-bottom: 18px;
}
.booking-root .stepper { display: flex; gap: 22px; }
.booking-root .stp { display: flex; align-items: center; gap: 10px; opacity: 0.5; }
.booking-root .stp.on, .booking-root .stp.done { opacity: 1; }
.booking-root .stp-dot {
    width: 26px; height: 26px; border-radius: 999px;
    border: 1px solid var(--ed-rule);
    display: flex; align-items: center; justify-content: center;
    font-size: 12px; font-family: 'Fraunces', serif;
    background: var(--ed-paper);
}
.booking-root .stp.on .stp-dot  { background: var(--ed-ink); color: var(--ed-paper); border-color: var(--ed-ink); }
.booking-root .stp.done .stp-dot { background: var(--ed-gold); color: var(--ed-paper); border-color: var(--ed-gold); }
.booking-root .stp-l { font-size: 12px; letter-spacing: 0.12em; text-transform: uppercase; }

.booking-root .booking-main { padding: 44px 56px 72px; }

/* Calendar / intro / hours */
.booking-root .calendar-wrap {
    display: grid; grid-template-columns: 1fr 1.35fr 0.95fr;
    gap: 32px; align-items: start;
    max-width: 1600px; margin: 0 auto;
}
.booking-root .eyebrow {
    font-size: 11px; letter-spacing: 0.22em; text-transform: uppercase;
    color: var(--ed-gold); font-weight: 500;
}
.booking-root .h1 {
    font-family: 'Fraunces', serif; font-weight: 400;
    font-size: 56px; line-height: 1.04; margin: 20px 0 22px;
    letter-spacing: -0.01em; color: var(--ed-ink);
}
.booking-root .h1 em { font-family: 'Instrument Serif', serif; font-style: italic; font-weight: 400; color: var(--ed-gold); }
.booking-root .lede { font-size: 15px; line-height: 1.65; color: var(--ed-ink-2); max-width: 36ch; }
.booking-root .bullets { list-style: none; padding: 0; margin: 32px 0 0; border-top: 1px solid var(--ed-rule); }
.booking-root .bullets li {
    display: flex; gap: 16px; padding: 16px 0;
    border-bottom: 1px solid var(--ed-rule);
    font-size: 14px; color: var(--ed-ink-2);
}
.booking-root .bullets li span {
    font-family: 'Fraunces', serif; font-style: italic;
    color: var(--ed-gold); min-width: 24px;
}

.booking-root .panel { background: var(--ed-paper); border: 1px solid var(--ed-rule); padding: 28px 28px 24px; }
.booking-root .panel-head {
    display: flex; justify-content: space-between; align-items: flex-end;
    margin-bottom: 22px; padding-bottom: 18px; border-bottom: 1px solid var(--ed-rule);
}
.booking-root .panel-eyebrow { font-size: 10px; letter-spacing: 0.22em; text-transform: uppercase; color: var(--ed-muted); }
.booking-root .panel-title { font-family: 'Fraunces', serif; font-size: 26px; font-weight: 400; margin-top: 6px; letter-spacing: -0.01em; }
.booking-root .monthnav { display: flex; gap: 4px; }
.booking-root .monthnav button { width: 36px; height: 36px; border: 1px solid var(--ed-rule); font-size: 18px; color: var(--ed-ink); transition: all 0.15s; }
.booking-root .monthnav button:hover { background: var(--ed-ink); color: var(--ed-paper); border-color: var(--ed-ink); }

.booking-root .monthgrid .dow { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; margin-bottom: 6px; }
.booking-root .monthgrid .dow > div { text-align: center; font-size: 10px; letter-spacing: 0.18em; text-transform: uppercase; color: var(--ed-muted); padding: 8px 0; }
.booking-root .wk { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; }
.booking-root .day {
    aspect-ratio: 1; display: flex; flex-direction: column; align-items: center; justify-content: center;
    border: 1px solid transparent; position: relative;
    font-family: 'Fraunces', serif; font-size: 18px; color: var(--ed-ink);
    background: transparent; transition: all 0.15s;
}
.booking-root .day:not(:disabled):hover { background: #efeadc; border-color: var(--ed-rule); }
.booking-root .day.outside { color: transparent; pointer-events: none; }
.booking-root .day.past, .booking-root .day.weekend { color: #c9c3b4; }
.booking-root .day.today { box-shadow: inset 0 0 0 1px var(--ed-gold-soft); }
.booking-root .day.selected { background: var(--ed-ink); color: var(--ed-paper); border-color: var(--ed-ink); }
.booking-root .day.selected .daydot { background: var(--ed-gold); }
.booking-root .daydot { width: 4px; height: 4px; border-radius: 999px; background: var(--ed-gold-soft); margin-top: 4px; opacity: 0.8; }
.booking-root .day.past .daydot, .booking-root .day.weekend .daydot { display: none; }

.booking-root .legend {
    display: flex; gap: 22px; margin-top: 18px; padding-top: 16px;
    border-top: 1px solid var(--ed-rule);
    font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--ed-muted);
}
.booking-root .legend span { display: flex; align-items: center; gap: 8px; }
.booking-root .legend i { width: 10px; height: 10px; display: inline-block; }
.booking-root .lg-open { background: var(--ed-gold-soft); border-radius: 999px; }
.booking-root .lg-sel { background: var(--ed-ink); }
.booking-root .lg-off { background: repeating-linear-gradient(-45deg, #c9c3b4, #c9c3b4 2px, transparent 2px, transparent 5px); border: 1px solid #c9c3b4; }

.booking-root .hours-panel.empty { background: transparent; border-style: dashed; }
.booking-root .empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; color: var(--ed-muted); padding: 60px 0; text-align: center; }
.booking-root .empty-icon { color: var(--ed-gold-soft); }

.booking-root .hourlist { display: flex; flex-direction: column; gap: 6px; }
.booking-root .hour {
    display: flex; justify-content: space-between; align-items: center;
    padding: 14px 18px; border: 1px solid var(--ed-rule); background: var(--ed-paper);
    text-align: left; transition: all 0.15s;
}
.booking-root .hourtime { font-family: 'Fraunces', serif; font-size: 17px; }
.booking-root .hourstate { font-size: 10px; letter-spacing: 0.18em; text-transform: uppercase; color: var(--ed-muted); }
.booking-root .hour:not(:disabled):hover { border-color: var(--ed-ink); }
.booking-root .hour.selected { background: var(--ed-ink); color: var(--ed-paper); border-color: var(--ed-ink); }
.booking-root .hour.selected .hourstate { color: var(--ed-gold-soft); }
.booking-root .hour.unavailable { color: #c9c3b4; background: repeating-linear-gradient(-45deg, transparent, transparent 6px, rgba(0,0,0,0.02) 6px, rgba(0,0,0,0.02) 7px); }

.booking-root .cta {
    margin-top: 24px; width: 100%; padding: 16px 20px;
    background: var(--ed-ink); color: var(--ed-paper);
    font-family: 'Fraunces', serif; font-size: 16px; letter-spacing: 0.02em;
    transition: all 0.15s;
}
.booking-root .cta:disabled { background: #c9c3b4; color: var(--ed-paper); }
.booking-root .cta:not(:disabled):hover { background: var(--ed-gold); }

/* Formular */
.booking-root .form-wrap { display: grid; grid-template-columns: 0.8fr 1.2fr; gap: 40px; max-width: 1300px; margin: 0 auto; }
.booking-root .summary {
    background: var(--ed-ink); color: var(--ed-paper);
    padding: 36px 32px; position: sticky; top: calc(var(--header-height) + 20px); align-self: start;
}
.booking-root .summary-eyebrow { font-size: 10px; letter-spacing: 0.22em; text-transform: uppercase; color: var(--ed-gold-soft); }
.booking-root .summary-when { margin: 18px 0 28px; padding-bottom: 28px; border-bottom: 1px solid rgba(255,255,255,0.14); }
.booking-root .summary-date { font-family: 'Fraunces', serif; font-size: 28px; font-weight: 400; line-height: 1.1; color: var(--ed-paper); }
.booking-root .summary-hour { font-family: 'Fraunces', serif; font-style: italic; font-size: 22px; color: var(--ed-gold-soft); margin-top: 8px; }
.booking-root .summary-meta { margin: 0; display: flex; flex-direction: column; gap: 14px; }
.booking-root .summary-meta > div { display: flex; justify-content: space-between; gap: 16px; font-size: 13px; padding-bottom: 12px; border-bottom: 1px solid rgba(255,255,255,0.08); }
.booking-root .summary-meta dt { color: var(--ed-gold-soft); text-transform: uppercase; letter-spacing: 0.14em; font-size: 10px; }
.booking-root .summary-meta dd { margin: 0; color: var(--ed-paper); }
.booking-root .ghost-back { margin-top: 28px; color: var(--ed-gold-soft); font-size: 12px; letter-spacing: 0.16em; text-transform: uppercase; padding: 0; }

.booking-root .h2 { font-family: 'Fraunces', serif; font-weight: 400; font-size: 42px; line-height: 1.08; margin: 14px 0 14px; letter-spacing: -0.01em; color: var(--ed-ink); }
.booking-root .h2 em { font-family: 'Instrument Serif', serif; font-style: italic; color: var(--ed-gold); }
.booking-root .lede-sm { font-size: 14px; line-height: 1.6; color: var(--ed-ink-2); max-width: 54ch; }

.booking-root .grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px 24px; margin-top: 28px; }
.booking-root .field { display: flex; flex-direction: column; gap: 6px; }
.booking-root .field .lab { font-size: 10px; letter-spacing: 0.18em; text-transform: uppercase; color: var(--ed-muted); }
.booking-root .field input, .booking-root .field textarea {
    font-family: 'Fraunces', serif; font-size: 18px; padding: 10px 0;
    border: none; border-bottom: 1px solid var(--ed-rule);
    background: transparent; color: var(--ed-ink); outline: none; transition: border 0.15s;
}
.booking-root .field input:focus, .booking-root .field textarea:focus { border-color: var(--ed-ink); }
.booking-root .field textarea { resize: vertical; font-family: 'Inter', sans-serif; font-size: 15px; line-height: 1.6; }
.booking-root .field.has-err input, .booking-root .field.has-err textarea { border-color: #a33; }
.booking-root .hint { font-size: 12px; color: var(--ed-muted); font-style: italic; }
.booking-root .err { font-size: 12px; color: #a33; }

.booking-root .seg { display: flex; gap: 0; margin-top: 4px; border: 1px solid var(--ed-rule); }
.booking-root .seg button {
    flex: 1; padding: 10px 12px; font-size: 12px; letter-spacing: 0.06em;
    color: var(--ed-ink-2); background: transparent;
    border-right: 1px solid var(--ed-rule);
}
.booking-root .seg button:last-child { border-right: none; }
.booking-root .seg button.on { background: var(--ed-ink); color: var(--ed-paper); }

.booking-root .field:has(textarea), .booking-root .disclaimer { margin-top: 24px; }
.booking-root .disclaimer {
    padding: 14px 16px; background: rgba(160,122,42,0.06);
    border-left: 2px solid var(--ed-gold);
    font-size: 12px; line-height: 1.5; color: var(--ed-ink-2);
}
.booking-root .actions { display: flex; justify-content: space-between; margin-top: 28px; gap: 14px; }
.booking-root .ghost { padding: 14px 28px; background: transparent; border: 1px solid var(--ed-rule); color: var(--ed-ink); font-family: 'Fraunces', serif; font-size: 15px; }
.booking-root .actions .cta { width: auto; flex: 1; max-width: 340px; margin-top: 0; }

/* Confirmare */
.booking-root .confirm-wrap { max-width: 780px; margin: 0 auto; }
.booking-root .confirm-card { background: var(--ed-paper); border: 1px solid var(--ed-rule); padding: 56px 60px; text-align: left; }
.booking-root .confirm-ico { color: var(--ed-gold); margin-bottom: 18px; }
.booking-root .ref { font-family: 'JetBrains Mono', monospace; font-size: 13px; background: rgba(27,36,50,0.06); padding: 2px 8px; }
.booking-root .confirm-grid {
    display: grid; grid-template-columns: 1fr 1fr; gap: 0;
    margin-top: 32px; border-top: 1px solid var(--ed-rule); border-left: 1px solid var(--ed-rule);
}
.booking-root .confirm-grid > div { padding: 18px 20px; border-right: 1px solid var(--ed-rule); border-bottom: 1px solid var(--ed-rule); }
.booking-root .confirm-grid .wide { grid-column: 1 / -1; }
.booking-root .confirm-grid .k { font-size: 10px; letter-spacing: 0.2em; text-transform: uppercase; color: var(--ed-muted); }
.booking-root .confirm-grid .v { font-family: 'Fraunces', serif; font-size: 18px; margin-top: 6px; }
.booking-root .confirm-grid .v.matter { font-style: italic; font-size: 16px; color: var(--ed-ink-2); line-height: 1.55; }
.booking-root .confirm-grid .muted { color: var(--ed-muted); font-size: 13px; font-style: italic; }
.booking-root .nextsteps { margin-top: 36px; padding: 24px 28px; background: var(--ed-ink); color: var(--ed-paper); }
.booking-root .ns-t { font-size: 10px; letter-spacing: 0.22em; text-transform: uppercase; color: var(--ed-gold-soft); margin-bottom: 12px; }
.booking-root .nextsteps ol { margin: 0; padding-left: 20px; font-family: 'Fraunces', serif; font-size: 17px; line-height: 1.7; color: var(--ed-paper); }

/* Responsive */
@media (max-width: 1100px) {
    .booking-root .calendar-wrap { grid-template-columns: 1fr; }
    .booking-root .form-wrap { grid-template-columns: 1fr; }
    .booking-root .summary { position: static; }
}
@media (max-width: 768px) {
    .booking-root .booking-topstrip { padding: 16px 20px; }
    .booking-root .booking-main { padding: 28px 20px 56px; }
    .booking-root .h1 { font-size: 40px; }
    .booking-root .h2 { font-size: 30px; }
    .booking-root .confirm-card { padding: 32px 22px; }
    .booking-root .confirm-grid { grid-template-columns: 1fr; }
    .booking-root .stepper { gap: 10px; }
    .booking-root .stp-l { display: none; }
    .booking-root .grid2 { grid-template-columns: 1fr; }
}
</style>

<div class="booking-root">
    <div class="booking-topstrip">
        <div class="stepper" id="bookingStepper">
            <!-- React populates stepper items here, but we mirror the shell so it looks right on first paint -->
        </div>
    </div>
    <main class="booking-main">
        <div id="bookingRoot"></div>
    </main>
</div>

<script>
    // Initial language fed from PHP (site-level RO/EN switcher drives this).
    window.PP_BOOKING_LANG = <?php echo json_encode($lang); ?>;
</script>

<script src="https://unpkg.com/react@18.3.1/umd/react.production.min.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.production.min.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/@babel/standalone@7.29.0/babel.min.js" crossorigin="anonymous"></script>

<script type="text/babel" data-presets="react">
/* global React, ReactDOM */
const { useState, useEffect, useMemo } = React;

// ---------- i18n ----------
const I18N = {
  en: {
    locale: 'en-GB',
    months: ['January','February','March','April','May','June','July','August','September','October','November','December'],
    daysLong: ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],
    daysShort: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],
    steps: ['Select time', 'Your details', 'Confirmed'],
    eyebrowBook: 'Book an appointment',
    h1Prefix: 'A considered conversation about your ',
    h1Em: 'matter.',
    lede: (s,e) => `Choose a weekday and an hour slot between ${s} and ${e}. We estimate that a consultation will last one hour and may be held by video, phone or at our office in Bucharest. If you feel a longer meeting is needed, please mention this in the final section of the booking, under the matter details.`,
    bullets: ['Choose an available hour','Share a short description of your matter','Receive confirmation by email'],
    availabilityEyebrow: (month, year) => `${month} ${year} — availability`,
    prevMonth: 'Previous month', nextMonth: 'Next month',
    availableHours: 'Available hours',
    pickDate: 'Select a date',
    pickDateHint: 'Pick a date on the left to see open hours.',
    booked: 'Booked', selected: 'Selected', available: 'Available',
    legOpen: 'Open', legSel: 'Selected', legOff: 'Unavailable',
    continueCta: 'Continue with this slot →',
    formEyebrow: 'Your details',
    formH2Prefix: 'So we may prepare ',
    formH2Em: 'properly.',
    formLede: 'Everything you share is held in strict confidence. We will review your description before the consultation so that our time together is used well.',
    fullName: 'Full name',
    email: 'Email address',
    phone: 'Phone',
    format: 'Preferred meeting format',
    matter: 'Brief description of your matter',
    matterHint: 'A sentence or two is enough. We will not share this with anyone outside the firm.',
    matterPh: 'e.g. We are acquiring a small logistics company and would like a view on the tax structure before we sign the LOI.',
    namePh: 'e.g. Andrei Ionescu',
    emailPh: 'name@company.ro',
    phonePh: '+40 7XX XXX XXX',
    formats: ['Video call', 'Phone call', 'In person — Bucharest office'],
    disclaimer: (addr) => <>Submitting this form does not create a lawyer–client relationship. A confirmation will be sent to your email and to <strong>{addr}</strong>.</>,
    back: 'Back',
    changeTime: '← Change time',
    confirmCta: 'Confirm appointment',
    yourAppointment: 'Your appointment',
    duration: 'Duration',
    durationVal: '60 minutes',
    location: 'Location',
    fee: 'Fee',
    feeVal: 'Depending on the matter',
    language: 'Language',
    errRequired: 'Required',
    errEmail: 'Invalid email',
    errMatter: 'Please describe your matter briefly',
    confirmed: 'Appointment confirmed',
    confirmH2Prefix: 'We look forward to meeting you, ',
    confirmH2Suffix: '.',
    confirmLede: (email, sentTo, ref) => <>A confirmation has been sent to <strong>{email}</strong> and to <strong>{sentTo}</strong>. Reference <span className="ref">{ref}</span>.</>,
    kDate: 'Date', kTime: 'Time', kFormat: 'Format', kDuration: 'Duration', kMatter: 'Matter',
    tz: '(EET)',
    whatsNext: 'What happens next',
    nextSteps: [
      'A partner will review your note before the call.',
      'You will receive joining details 24 hours in advance.',
      'If anything changes, reschedule from the email link.',
    ],
    bookAnother: 'Book another time',
    addCal: 'Add to my calendar',
    addedIcs: '✓ Downloaded .ics',
    icsSummary: (firm) => `Legal consultation — ${firm}`,
    dateFmt: (d) => `${I18N.en.daysLong[(d.getDay()+6)%7]}, ${I18N.en.months[d.getMonth()]} ${d.getDate()}`,
  },
  ro: {
    locale: 'ro-RO',
    months: ['Ianuarie','Februarie','Martie','Aprilie','Mai','Iunie','Iulie','August','Septembrie','Octombrie','Noiembrie','Decembrie'],
    daysLong: ['Luni','Marți','Miercuri','Joi','Vineri','Sâmbătă','Duminică'],
    daysShort: ['Lun','Mar','Mie','Joi','Vin','Sâm','Dum'],
    steps: ['Alege ora', 'Datele tale', 'Confirmat'],
    eyebrowBook: 'Programare consultație',
    h1Prefix: 'O conversație atentă despre ',
    h1Em: 'cazul dumneavoastră.',
    lede: (s,e) => `Alegeți o zi lucrătoare și un interval orar între ${s} și ${e}. Estimăm că o consultație va dura o oră și se poate desfășura prin video, telefon sau la sediul nostru din București. În cazul în care considerați necesar un timp mai îndelungat pentru întâlnire, vă rugăm să includeți această solicitare în secțiunea finală a programării, la rubrica detalii.`,
    bullets: ['Alegeți o oră disponibilă','Descrieți pe scurt situația dumneavoastră','Primiți confirmarea pe e-mail'],
    availabilityEyebrow: (month, year) => `${month} ${year} — disponibilitate`,
    prevMonth: 'Luna precedentă', nextMonth: 'Luna următoare',
    availableHours: 'Ore disponibile',
    pickDate: 'Alegeți o dată',
    pickDateHint: 'Alegeți o dată din stânga pentru a vedea orele libere.',
    booked: 'Ocupat', selected: 'Selectat', available: 'Liber',
    legOpen: 'Liber', legSel: 'Selectat', legOff: 'Indisponibil',
    continueCta: 'Continuă cu acest interval →',
    formEyebrow: 'Datele dumneavoastră',
    formH2Prefix: 'Pentru a ne pregăti ',
    formH2Em: 'corespunzător.',
    formLede: 'Tot ce ne transmiteți este tratat cu strictă confidențialitate. Vom analiza descrierea înainte de consultație pentru ca timpul împreună să fie folosit eficient.',
    fullName: 'Nume complet',
    email: 'Adresă de e-mail',
    phone: 'Telefon',
    format: 'Format preferat al întâlnirii',
    matter: 'Descriere succintă a cazului',
    matterHint: 'Una sau două fraze sunt suficiente. Informația nu va fi comunicată în afara firmei.',
    matterPh: 'ex. Achiziționăm o companie de logistică și dorim o opinie asupra structurii fiscale înainte de semnarea LOI-ului.',
    namePh: 'ex. Andrei Ionescu',
    emailPh: 'nume@companie.ro',
    phonePh: '+40 7XX XXX XXX',
    formats: ['Apel video', 'Apel telefonic', 'În persoană — sediul din București'],
    disclaimer: (addr) => <>Completarea acestui formular nu creează o relație avocat–client. O confirmare va fi trimisă pe adresa dumneavoastră și la <strong>{addr}</strong>.</>,
    back: 'Înapoi',
    changeTime: '← Schimbă ora',
    confirmCta: 'Confirmă programarea',
    yourAppointment: 'Programarea dumneavoastră',
    duration: 'Durată',
    durationVal: '60 de minute',
    location: 'Locație',
    fee: 'Onorariu',
    feeVal: 'În funcție de caz',
    language: 'Limbă',
    errRequired: 'Obligatoriu',
    errEmail: 'E-mail invalid',
    errMatter: 'Vă rugăm descrieți pe scurt cazul',
    confirmed: 'Programare confirmată',
    confirmH2Prefix: 'Vă așteptăm cu plăcere, ',
    confirmH2Suffix: '.',
    confirmLede: (email, sentTo, ref) => <>O confirmare a fost trimisă la <strong>{email}</strong> și la <strong>{sentTo}</strong>. Referință <span className="ref">{ref}</span>.</>,
    kDate: 'Data', kTime: 'Ora', kFormat: 'Format', kDuration: 'Durată', kMatter: 'Caz',
    tz: '(EET)',
    whatsNext: 'Ce urmează',
    nextSteps: [
      'Un partener va citi nota dumneavoastră înainte de întâlnire.',
      'Veți primi detaliile de conectare cu 24 de ore înainte.',
      'Dacă intervine o schimbare, puteți reprograma din e-mail.',
    ],
    bookAnother: 'Programează alt interval',
    addCal: 'Adaugă în calendarul meu',
    addedIcs: '✓ Fișier .ics descărcat',
    icsSummary: (firm) => `Consultație juridică — ${firm}`,
    dateFmt: (d) => `${I18N.ro.daysLong[(d.getDay()+6)%7]}, ${d.getDate()} ${I18N.ro.months[d.getMonth()].toLowerCase()}`,
  },
};

const FIRM_NAME = 'Petcu Partners';
const OFFICE_EMAIL = 'office@petcupartners.ro';
const WORK_START = 9;
const WORK_END = 17;
const HOURS = [9,10,11,12,13,14,15,16];

// ---------- helpers ----------
function buildMonthGrid(year, month) {
  const first = new Date(year, month, 1);
  const startOffset = (first.getDay() + 6) % 7;
  const start = new Date(year, month, 1 - startOffset);
  const weeks = [];
  for (let w = 0; w < 6; w++) {
    const week = [];
    for (let d = 0; d < 7; d++) {
      const day = new Date(start);
      day.setDate(start.getDate() + w * 7 + d);
      week.push(day);
    }
    weeks.push(week);
  }
  return weeks;
}
function sameDay(a, b) { return a.getFullYear()===b.getFullYear() && a.getMonth()===b.getMonth() && a.getDate()===b.getDate(); }
function isoDate(d) { return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; }
function computeAvailability(dateKey) {
  // Pseudorandom deterministic availability per day. In production this would come from the server.
  let h = 0;
  for (let i = 0; i < dateKey.length; i++) h = (h * 31 + dateKey.charCodeAt(i)) >>> 0;
  const hours = [9,10,11,12,13,14,15,16];
  const blocked = new Set();
  if (h % 5 !== 0) blocked.add(13);
  blocked.add(hours[h % hours.length]);
  if ((h >> 3) % 3 === 0) blocked.add(hours[(h >> 3) % hours.length]);
  return blocked;
}
function fmtHour(h) { return `${String(h).padStart(2,'0')}:00`; }

function downloadIcs(c, firmName, t) {
  const pad = n => String(n).padStart(2,'0');
  const d = c.date;
  const dtStart = `${d.getFullYear()}${pad(d.getMonth()+1)}${pad(d.getDate())}T${pad(c.hour)}0000`;
  const dtEnd   = `${d.getFullYear()}${pad(d.getMonth()+1)}${pad(d.getDate())}T${pad(c.hour+1)}0000`;
  const now = new Date();
  const dtStamp = `${now.getUTCFullYear()}${pad(now.getUTCMonth()+1)}${pad(now.getUTCDate())}T${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}Z`;
  const esc = s => String(s||'').replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/,/g,'\\,').replace(/;/g,'\\;');
  const ics = [
    'BEGIN:VCALENDAR','VERSION:2.0','PRODID:-//Petcu Partners//Booking//EN','CALSCALE:GREGORIAN','METHOD:PUBLISH',
    'BEGIN:VTIMEZONE','TZID:Europe/Bucharest','BEGIN:STANDARD','DTSTART:20261025T040000','TZOFFSETFROM:+0300','TZOFFSETTO:+0200','TZNAME:EET','END:STANDARD','BEGIN:DAYLIGHT','DTSTART:20260329T030000','TZOFFSETFROM:+0200','TZOFFSETTO:+0300','TZNAME:EEST','END:DAYLIGHT','END:VTIMEZONE',
    'BEGIN:VEVENT',`UID:${c.ref}@petcupartners.ro`,`DTSTAMP:${dtStamp}`,`DTSTART;TZID=Europe/Bucharest:${dtStart}`,`DTEND;TZID=Europe/Bucharest:${dtEnd}`,
    `SUMMARY:${esc(t.icsSummary(firmName))}`,
    `DESCRIPTION:${esc(`${c.meetingType}\nMatter: ${c.matter}\nReference: ${c.ref}\nContact: ${OFFICE_EMAIL}`)}`,
    `LOCATION:${esc(c.meetingType)}`,
    `ORGANIZER;CN=${esc(firmName)}:mailto:${OFFICE_EMAIL}`,
    `ATTENDEE;CN=${esc(c.name)};RSVP=TRUE:mailto:${c.email}`,
    'STATUS:CONFIRMED','END:VEVENT','END:VCALENDAR'
  ].join('\r\n');
  const blob = new Blob([ics], { type: 'text/calendar;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = `petcu-partners-${c.ref}.ics`;
  document.body.appendChild(a); a.click(); document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

// ---------- Stepper rendered outside the main React root (top strip) ----------
function Stepper({ t, stepIdx }) {
  return (
    <>
      {t.steps.map((l,i) => (
        <div key={i} className={`stp ${i===stepIdx?'on':''} ${i<stepIdx?'done':''}`}>
          <div className="stp-dot">{i<stepIdx?'✓':i+1}</div>
          <div className="stp-l">{l}</div>
        </div>
      ))}
    </>
  );
}

// ---------- Booking app ----------
function BookingApp() {
  const lang = (window.PP_BOOKING_LANG === 'en') ? 'en' : 'ro';
  const t = I18N[lang];

  const today = useMemo(() => { const d = new Date(); d.setHours(0,0,0,0); return d; }, []);
  const [viewYear, setViewYear] = useState(today.getFullYear());
  const [viewMonth, setViewMonth] = useState(today.getMonth());
  const [selectedDate, setSelectedDate] = useState(null);
  const [selectedHour, setSelectedHour] = useState(null);
  const [step, setStep] = useState('calendar');
  const [meetingTypeIdx, setMeetingTypeIdx] = useState(0);
  const [form, setForm] = useState({ name: '', email: '', phone: '', matter: '' });
  const [errors, setErrors] = useState({});
  const [confirmation, setConfirmation] = useState(null);

  const weeks = useMemo(() => buildMonthGrid(viewYear, viewMonth), [viewYear, viewMonth]);
  const visibleHours = HOURS.filter(h => h >= WORK_START && h < WORK_END);
  const availability = useMemo(() => selectedDate ? computeAvailability(isoDate(selectedDate)) : new Set(), [selectedDate]);
  const isSelectable = (d) => {
    if (d.getMonth() !== viewMonth) return false;
    if (d < today) return false;
    const dow = d.getDay();
    return dow !== 0 && dow !== 6;
  };

  const pickDay = (d) => { if (isSelectable(d)) { setSelectedDate(d); setSelectedHour(null); } };
  const pickHour = (h) => { if (!availability.has(h)) setSelectedHour(h); };
  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = t.errRequired;
    if (!form.email.trim()) e.email = t.errRequired;
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = t.errEmail;
    if (!form.phone.trim()) e.phone = t.errRequired;
    if (!form.matter.trim()) e.matter = t.errMatter;
    setErrors(e);
    return Object.keys(e).length === 0;
  };
  const submit = () => {
    if (!validate()) return;
    const ref = `PP-${Date.now().toString(36).toUpperCase().slice(-6)}`;
    const payload = {
      ref, date: selectedDate, hour: selectedHour,
      meetingType: t.formats[meetingTypeIdx], meetingTypeIdx,
      ...form, sentTo: OFFICE_EMAIL,
    };
    setConfirmation(payload);
    setStep('confirmation');

    // Notify the firm via the server-side endpoint (best-effort, fire-and-forget)
    try {
      const fd = new FormData();
      fd.append('ref', ref);
      fd.append('lang', lang);
      fd.append('date', isoDate(selectedDate));
      fd.append('hour', String(selectedHour));
      fd.append('format', t.formats[meetingTypeIdx]);
      fd.append('name', form.name);
      fd.append('email', form.email);
      fd.append('phone', form.phone);
      fd.append('matter', form.matter);
      fetch('trimite-programare.php', { method: 'POST', body: fd }).catch(()=>{});
    } catch(e) {}

    try { window.scrollTo({ top: 0, behavior: 'smooth' }); } catch(e) {}
  };
  const resetAll = () => {
    setSelectedDate(null); setSelectedHour(null); setStep('calendar');
    setForm({ name:'', email:'', phone:'', matter:''}); setErrors({});
    setMeetingTypeIdx(0); setConfirmation(null);
  };

  const stepIdx = step === 'calendar' ? 0 : step === 'form' ? 1 : 2;

  // Render stepper into the top strip (outside this React root).
  useEffect(() => {
    const host = document.getElementById('bookingStepper');
    if (!host) return;
    if (!host._root) host._root = ReactDOM.createRoot(host);
    host._root.render(<Stepper t={t} stepIdx={stepIdx} />);
  }, [stepIdx, lang]);

  return (
    <>
      {step === 'calendar' && (
        <CalendarStep
          t={t} weeks={weeks} viewYear={viewYear} viewMonth={viewMonth}
          goPrev={()=>{ const m=viewMonth-1; if(m<0){setViewMonth(11); setViewYear(viewYear-1);} else setViewMonth(m); }}
          goNext={()=>{ const m=viewMonth+1; if(m>11){setViewMonth(0); setViewYear(viewYear+1);} else setViewMonth(m); }}
          today={today} selectedDate={selectedDate} onPickDay={pickDay}
          selectedHour={selectedHour} onPickHour={pickHour}
          visibleHours={visibleHours} availability={availability}
          workStart={WORK_START} workEnd={WORK_END}
          onContinue={() => { if (selectedDate && selectedHour != null) setStep('form'); }}
        />
      )}
      {step === 'form' && (
        <FormStep
          t={t} date={selectedDate} hour={selectedHour}
          form={form} setForm={setForm} errors={errors}
          meetingTypeIdx={meetingTypeIdx} setMeetingTypeIdx={setMeetingTypeIdx}
          onBack={() => setStep('calendar')} onSubmit={submit}
        />
      )}
      {step === 'confirmation' && confirmation && (
        <ConfirmationStep t={t} c={confirmation} onReset={resetAll} firmName={FIRM_NAME} />
      )}
    </>
  );
}

function CalendarStep({ t, weeks, viewYear, viewMonth, goPrev, goNext, today, selectedDate, onPickDay, selectedHour, onPickHour, visibleHours, availability, workStart, workEnd, onContinue }) {
  return (
    <div className="calendar-wrap">
      <section className="intro">
        <div className="eyebrow">{t.eyebrowBook}</div>
        <h1 className="h1">{t.h1Prefix}<em>{t.h1Em}</em></h1>
        <p className="lede">{t.lede(fmtHour(workStart), fmtHour(workEnd))}</p>
        <ul className="bullets">
          {t.bullets.map((b,i) => <li key={i}><span>{String(i+1).padStart(2,'0')}</span> {b}</li>)}
        </ul>
      </section>

      <section className="panel calendar-panel">
        <div className="panel-head">
          <div>
            <div className="panel-eyebrow">{t.availabilityEyebrow(t.months[viewMonth], viewYear)}</div>
            <div className="panel-title">{t.months[viewMonth]} {viewYear}</div>
          </div>
          <div className="monthnav">
            <button onClick={goPrev} aria-label={t.prevMonth}>‹</button>
            <button onClick={goNext} aria-label={t.nextMonth}>›</button>
          </div>
        </div>

        <div className="monthgrid">
          <div className="dow">
            {t.daysShort.map(d => <div key={d}>{d}</div>)}
          </div>
          {weeks.map((wk, wi) => (
            <div className="wk" key={wi}>
              {wk.map((d, di) => {
                const outside = d.getMonth() !== viewMonth;
                const past = d < today;
                const weekend = d.getDay() === 0 || d.getDay() === 6;
                const disabled = outside || past || weekend;
                const selected = selectedDate && sameDay(d, selectedDate);
                const isToday = sameDay(d, today);
                return (
                  <button key={di}
                    className={`day ${outside?'outside':''} ${past?'past':''} ${weekend?'weekend':''} ${selected?'selected':''} ${isToday?'today':''}`}
                    disabled={disabled} onClick={() => onPickDay(d)}>
                    <span className="daynum">{d.getDate()}</span>
                    {!disabled && <span className="daydot" />}
                  </button>
                );
              })}
            </div>
          ))}
        </div>

        <div className="legend">
          <span><i className="lg-open" /> {t.legOpen}</span>
          <span><i className="lg-sel" /> {t.legSel}</span>
          <span><i className="lg-off" /> {t.legOff}</span>
        </div>
      </section>

      <section className={`panel hours-panel ${!selectedDate ? 'empty' : ''}`}>
        <div className="panel-head">
          <div>
            <div className="panel-eyebrow">{t.availableHours}</div>
            <div className="panel-title">
              {selectedDate ? t.dateFmt(selectedDate) : t.pickDate}
            </div>
          </div>
        </div>

        {!selectedDate ? (
          <div className="empty-state">
            <div className="empty-icon">
              <svg width="48" height="48" viewBox="0 0 48 48" fill="none">
                <rect x="6" y="10" width="36" height="32" rx="2" stroke="currentColor" strokeWidth="1.2"/>
                <path d="M6 18h36" stroke="currentColor" strokeWidth="1.2"/>
                <path d="M16 6v8M32 6v8" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/>
              </svg>
            </div>
            <div>{t.pickDateHint}</div>
          </div>
        ) : (
          <>
            <div className="hourlist">
              {visibleHours.map(h => {
                const unavailable = availability.has(h);
                const selected = selectedHour === h;
                return (
                  <button key={h}
                    className={`hour ${unavailable?'unavailable':''} ${selected?'selected':''}`}
                    disabled={unavailable} onClick={() => onPickHour(h)}>
                    <span className="hourtime">{fmtHour(h)} — {fmtHour(h+1)}</span>
                    <span className="hourstate">{unavailable ? t.booked : selected ? t.selected : t.available}</span>
                  </button>
                );
              })}
            </div>
            <button className="cta" disabled={selectedHour == null} onClick={onContinue}>
              {t.continueCta}
            </button>
          </>
        )}
      </section>
    </div>
  );
}

function FormStep({ t, date, hour, form, setForm, errors, meetingTypeIdx, setMeetingTypeIdx, onBack, onSubmit }) {
  const update = (k, v) => setForm({ ...form, [k]: v });
  return (
    <div className="form-wrap">
      <aside className="summary">
        <div className="summary-eyebrow">{t.yourAppointment}</div>
        <div className="summary-when">
          <div className="summary-date">{t.dateFmt(date)}</div>
          <div className="summary-hour">{fmtHour(hour)} — {fmtHour(hour+1)}</div>
        </div>
        <dl className="summary-meta">
          <div><dt>{t.duration}</dt><dd>{t.durationVal}</dd></div>
          <div><dt>{t.location}</dt><dd>{t.formats[meetingTypeIdx]}</dd></div>
          <div><dt>{t.fee}</dt><dd>{t.feeVal}</dd></div>
          <div><dt>{t.language}</dt><dd>RO · EN</dd></div>
        </dl>
        <button className="ghost-back" onClick={onBack}>{t.changeTime}</button>
      </aside>

      <section className="formbody">
        <div className="eyebrow">{t.formEyebrow}</div>
        <h2 className="h2">{t.formH2Prefix}<em>{t.formH2Em}</em></h2>
        <p className="lede-sm">{t.formLede}</p>

        <div className="grid2">
          <Field label={t.fullName} err={errors.name}>
            <input value={form.name} onChange={e=>update('name', e.target.value)} placeholder={t.namePh} />
          </Field>
          <Field label={t.email} err={errors.email}>
            <input type="email" value={form.email} onChange={e=>update('email', e.target.value)} placeholder={t.emailPh} />
          </Field>
          <Field label={t.phone} err={errors.phone}>
            <input type="tel" value={form.phone} onChange={e=>update('phone', e.target.value)} placeholder={t.phonePh} />
          </Field>
          <Field label={t.format} err={null}>
            <div className="seg">
              {t.formats.map((f, i) => (
                <button key={i} type="button" className={meetingTypeIdx===i?'on':''} onClick={()=>setMeetingTypeIdx(i)}>{f}</button>
              ))}
            </div>
          </Field>
        </div>

        <Field label={t.matter} err={errors.matter} hint={t.matterHint}>
          <textarea rows={5} value={form.matter} onChange={e=>update('matter', e.target.value)} placeholder={t.matterPh} />
        </Field>

        <div className="disclaimer">{t.disclaimer(OFFICE_EMAIL)}</div>

        <div className="actions">
          <button className="ghost" onClick={onBack}>{t.back}</button>
          <button className="cta" onClick={onSubmit}>{t.confirmCta}</button>
        </div>
      </section>
    </div>
  );
}

function Field({ label, err, hint, children }) {
  return (
    <label className={`field ${err?'has-err':''}`}>
      <span className="lab">{label}</span>
      {children}
      {hint && !err && <span className="hint">{hint}</span>}
      {err && <span className="err">{err}</span>}
    </label>
  );
}

function ConfirmationStep({ t, c, onReset, firmName }) {
  const [added, setAdded] = useState(false);
  const handleAdd = () => { downloadIcs(c, firmName, t); setAdded(true); setTimeout(() => setAdded(false), 2500); };
  const firstName = (c.name.split(' ')[0]) || '';
  return (
    <div className="confirm-wrap">
      <div className="confirm-card">
        <div className="confirm-ico">
          <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
            <circle cx="20" cy="20" r="19" stroke="currentColor" strokeWidth="1.2" />
            <path d="M12 20.5l6 6 12-13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>
        <div className="eyebrow">{t.confirmed}</div>
        <h2 className="h2">{t.confirmH2Prefix}<em>{firstName}</em>{t.confirmH2Suffix}</h2>
        <p className="lede-sm">{t.confirmLede(c.email, c.sentTo, c.ref)}</p>

        <div className="confirm-grid">
          <div><div className="k">{t.kDate}</div><div className="v">{t.dateFmt(c.date)}</div></div>
          <div><div className="k">{t.kTime}</div><div className="v">{fmtHour(c.hour)} — {fmtHour(c.hour+1)} <span className="muted">{t.tz}</span></div></div>
          <div><div className="k">{t.kFormat}</div><div className="v">{t.formats[c.meetingTypeIdx]}</div></div>
          <div><div className="k">{t.kDuration}</div><div className="v">{t.durationVal}</div></div>
          <div className="wide"><div className="k">{t.kMatter}</div><div className="v matter">“{c.matter}”</div></div>
        </div>

        <div className="nextsteps">
          <div className="ns-t">{t.whatsNext}</div>
          <ol>{t.nextSteps.map((s,i) => <li key={i}>{s}</li>)}</ol>
        </div>

        <div className="actions">
          <button className="ghost" onClick={onReset}>{t.bookAnother}</button>
          <button className="cta" onClick={handleAdd}>{added ? t.addedIcs : t.addCal}</button>
        </div>
      </div>
    </div>
  );
}

(function mount() {
  const el = document.getElementById('bookingRoot');
  if (!el) return setTimeout(mount, 30);
  ReactDOM.createRoot(el).render(<BookingApp />);
})();
</script>
