/* Fluffy Friends — multi-step booking modal (pre-fills a WhatsApp message) */
const { Button, Input, Select, Checkbox, Badge } = window.FluffyFriendsDesignSystem_a09c32;

const PET_OPTS = [
  { key: 'dog', label: 'Dog', icon: 'dog' },
  { key: 'cat', label: 'Cat', icon: 'cat' },
  { key: 'bird', label: 'Bird', icon: 'bird' },
  { key: 'rabbit', label: 'Rabbit', icon: 'rabbit' },
];

/* base price by pet + groom type. Dogs are priced by size (+AED 50 per tier). */
const BASE = {
  dog: {
    small:  { 'Basic groom': 200, 'Full groom': 250, 'Nail trimming': 50, 'Haircut only': 70 },
    medium: { 'Basic groom': 250, 'Full groom': 300, 'Nail trimming': 50, 'Haircut only': 70 },
    large:  { 'Basic groom': 300, 'Full groom': 350, 'Nail trimming': 50, 'Haircut only': 70 },
  },
  cat: {
    kitten: { 'Basic groom': 180, 'Full groom': 200, 'Nail trimming': 50, 'Haircut only': 70 },
    adult: { 'Basic groom': 200, 'Full groom': 250, 'Nail trimming': 50, 'Haircut only': 70 },
  },
  bird: { 'Small bird': 120, 'Large bird': 170 },
  rabbit: { 'Full grooming': 150 },
};
const CAT_AGES = [
  { key: 'kitten', label: 'Kitten · up to 8 months' },
  { key: 'adult', label: 'Adult cat' },
];
const SERVICE_OPTS = {
  dog: ['Basic groom', 'Full groom', 'Nail trimming', 'Haircut only'],
  cat: ['Basic groom', 'Full groom', 'Nail trimming', 'Haircut only'],
  bird: ['Small bird', 'Large bird'],
  rabbit: ['Full grooming'],
};
// Quick add-on services have their own short durations (override the size/pet duration).
const SERVICE_DURATIONS = { 'Nail trimming': 30, 'Haircut only': 60 };
const EXTRAS = [
  { key: 'teeth', label: 'Teeth brushing / gland cleaning', price: 50 },
  { key: 'shampoo', label: 'Anti-allergy / medical shampoo', price: 30 },
  { key: 'ticks', label: 'Tick & fleas protection', price: 100 },
];

function BookingModal({ onClose, initialPet }) {
  const [step, setStep] = React.useState(1);
  const [pet, setPet] = React.useState(initialPet || 'dog');
  const [catAge, setCatAge] = React.useState('adult');
  const [size, setSize] = React.useState('small');
  const [service, setService] = React.useState('Full groom');
  const [extras, setExtras] = React.useState({});
  const [form, setForm] = React.useState({ name: '', mobile: '', petName: '', date: '', time: 'Morning (9–12)', area: '' });

  // keep service valid when pet changes
  React.useEffect(() => {
    const opts = SERVICE_OPTS[pet];
    if (!opts.includes(service)) setService(opts[0]);
    setExtras({});
  }, [pet]); // eslint-disable-line

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toggle = (k) => setExtras(e => ({ ...e, [k]: !e[k] }));

  const priceFor = (svc) => (pet === 'cat' ? (BASE.cat[catAge] || {})[svc]
    : pet === 'dog' ? (BASE.dog[size] || {})[svc]
    : (BASE[pet] || {})[svc]) || 0;
  const base = priceFor(service);
  const catAgeLabel = (CAT_AGES.find(a => a.key === catAge) || {}).label;
  const sizeName = size.charAt(0).toUpperCase() + size.slice(1);
  const dogSizeLabel = pet === 'dog' ? `${sizeName} dog` : '';
  const petDesc = pet === 'cat' ? `Cat (${catAge === 'kitten' ? 'Kitten, up to 8 months' : 'Adult'})`
    : pet === 'dog' ? `Dog (${sizeName})`
    : null;
  const extrasList = EXTRAS.filter(x => extras[x.key]);
  const extrasTotal = extrasList.reduce((s, x) => s + x.price, 0);
  const total = base + extrasTotal;
  const petLabel = PET_OPTS.find(p => p.key === pet).label;
  const showExtras = pet === 'dog' || pet === 'cat';

  const buildMessage = () => {
    const lines = [
      'Hi Fluffy Friends! 🐾 I\'d like to book a groom:',
      `• Pet: ${petDesc || petLabel}${form.petName ? ` — ${form.petName}` : ''}`,
      `• Service: ${service} — AED ${base}`,
    ];
    if (extrasList.length) lines.push(`• Add-ons: ${extrasList.map(x => `${x.label} (AED ${x.price})`).join(', ')}`);
    lines.push(`• Estimated total: AED ${total}`);
    if (form.date) lines.push(`• Preferred date: ${form.date}`);
    lines.push(`• Time: ${form.time}`);
    if (form.name) lines.push(`• Name: ${form.name}`);
    if (form.mobile) lines.push(`• Mobile: ${form.mobile}`);
    if (form.area) lines.push(`• Area: ${form.area}`);
    return lines.join('\n');
  };

  const confirm = () => { openWhatsApp(buildMessage()); setStep(3); };

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        {step < 3 && (
          <div className="modal__head">
            <div>
              <h3>{step === 1 ? 'Book a groom' : 'Your details'}</h3>
            </div>
            <button className="modal__close" onClick={onClose} aria-label="Close"><Icon name="x" size={18} /></button>
          </div>
        )}

        {step === 1 && (
          <React.Fragment>
            <div className="modal__body">
              <div>
                <label className="fl-lab">Which friend are we grooming?</label>
                <div className="pet-pick">
                  {PET_OPTS.map(p => (
                    <button key={p.key} type="button" className={'pet-opt' + (pet === p.key ? ' on' : '')} onClick={() => setPet(p.key)}>
                      <Icon name={p.icon} size={26} stroke={pet === p.key ? 'var(--ink-900)' : 'var(--ink-500)'} /> {p.label}
                    </button>
                  ))}
                </div>
              </div>
              {pet === 'cat' && (
                <div>
                  <label className="fl-lab">How old is your cat?</label>
                  <Select value={catAge} onChange={e => setCatAge(e.target.value)}>
                    {CAT_AGES.map(a => <option key={a.key} value={a.key}>{a.label}</option>)}
                  </Select>
                </div>
              )}
              {pet === 'dog' && (
                <div>
                  <label className="fl-lab">How big is your dog?</label>
                  <Select value={size} onChange={e => setSize(e.target.value)}>
                    {DOG_SIZES.map(s => <option key={s.key} value={s.key}>{s.label}</option>)}
                  </Select>
                </div>
              )}
              <div>
                <label className="fl-lab">Choose a service</label>
                <Select value={service} onChange={e => setService(e.target.value)}>
                  {SERVICE_OPTS[pet].map(s => (
                    <option key={s} value={s}>{s} — AED {priceFor(s)}</option>
                  ))}
                </Select>
              </div>
              {showExtras && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
                  <label className="fl-lab" style={{ marginBottom: 0 }}>Add a little extra</label>
                  {EXTRAS.map(x => (
                    <Checkbox key={x.key} label={`${x.label} (+AED ${x.price})`} checked={!!extras[x.key]} onChange={() => toggle(x.key)} />
                  ))}
                </div>
              )}
              {pet === 'rabbit' && (
                <div className="price-note" style={{ marginTop: 0 }}>
                  <h4><Icon name="info" size={18} /> A note on rabbits</h4>
                  <p>We don&rsquo;t shower rabbits — we use safe, water-free spot-cleaning to keep them warm and healthy.</p>
                </div>
              )}
              <div className="summary">
                <div className="summary__row"><span>{pet === 'cat' ? `${service} · ${catAge === 'kitten' ? 'Kitten' : 'Adult cat'}` : service}</span><b>AED {base}</b></div>
                {extrasList.map(x => <div className="summary__row" key={x.key}><span>{x.label}</span><b>AED {x.price}</b></div>)}
                <div className="summary__row summary__total"><span>Estimated total</span><b>AED {total}</b></div>
              </div>
            </div>
            <div className="modal__foot">
              <div className="modal__progress"><span className="on" /><span /></div>
              <Button variant="primary" onClick={() => setStep(2)}>Continue</Button>
            </div>
          </React.Fragment>
        )}

        {step === 2 && (
          <React.Fragment>
            <div className="modal__body">
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                <Badge tone="soft">{petLabel}</Badge>
                {pet === 'cat' && <Badge tone="soft">{catAgeLabel}</Badge>}
                {pet === 'dog' && <Badge tone="soft">{dogSizeLabel}</Badge>}
                <Badge tone="pink">{service}</Badge>
                <Badge tone="ink">AED {total}</Badge>
              </div>
              <div className="modal__row">
                <Input label="Your name" placeholder="e.g. Mariam" value={form.name} onChange={e => set('name', e.target.value)} />
                <Input label="Pet's name" placeholder="e.g. Mochi" value={form.petName} onChange={e => set('petName', e.target.value)} />
              </div>
              <Input label="Mobile number" placeholder="+971 50 ..." value={form.mobile} onChange={e => set('mobile', e.target.value)} />
              <div className="modal__row">
                <Input label="Preferred date" type="date" value={form.date} onChange={e => set('date', e.target.value)} />
                <div>
                  <label className="fl-lab">Time</label>
                  <Select value={form.time} onChange={e => set('time', e.target.value)}>
                    <option>Morning (9–12)</option>
                    <option>Afternoon (12–4)</option>
                    <option>Evening (4–7)</option>
                  </Select>
                </div>
              </div>
              <Input label="Your address / area in Dubai" placeholder="Villa or building, area" value={form.area} onChange={e => set('area', e.target.value)} />
              <p style={{ fontSize: 13, color: 'var(--text-muted)', display: 'flex', gap: 8, alignItems: 'center' }}>
                <WhatsAppGlyph size={16} /> We&rsquo;ll open WhatsApp with your booking ready to send.
              </p>
            </div>
            <div className="modal__foot">
              <Button variant="ghost" onClick={() => setStep(1)}>Back</Button>
              <Button variant="primary" onClick={confirm}><WhatsAppGlyph size={18} /> Confirm on WhatsApp</Button>
            </div>
          </React.Fragment>
        )}

        {step === 3 && (
          <div className="success">
            <div className="success__ring"><Bunny src="flf-bunny-pink.png" style={{ width: 60 }} /></div>
            <h3>Sent to WhatsApp!</h3>
            <p>We&rsquo;ve opened a chat with your {petLabel.toLowerCase()}&rsquo;s {service.toLowerCase()} booking ready to send. We&rsquo;ll confirm your time and bring the pink van right to your door. See you soon!</p>
            <div style={{ marginTop: 26, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
              <Button variant="primary" size="lg" onClick={onClose}>Lovely, done</Button>
              <Button variant="ghost" onClick={() => openWhatsApp(buildMessage())}>Re-open WhatsApp</Button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

/* Typical groom time per pet (minutes), from historical booking durations.
   Drives how long a slot is reserved so the groomer's schedule is blocked
   accurately (esp. for multi-pet bookings). Dogs use size-based durations
   (see DOG_SIZES); cat/bird/rabbit use these flat estimates. */
const DURATIONS = { cat: 60, bird: 45, rabbit: 45 };

/* Dog size → typical groom duration (minutes), from the size-by-duration data. */
const DOG_SIZES = [
  { key: 'small',  label: 'Small dog · up to 8kg', duration: 60 },
  { key: 'medium', label: 'Medium dog · 8–15kg',   duration: 90 },
  { key: 'large',  label: 'Large dog · 15kg+',      duration: 120 },
];

Object.assign(window, { BookingModal, BOOKING_DATA: { PET_OPTS, BASE, CAT_AGES, SERVICE_OPTS, EXTRAS, DURATIONS, DOG_SIZES, SERVICE_DURATIONS } });
