// Guided concierge chat — WhatsApp availability flow for Pink Lady.
// Feels like a warm chat with Shira's studio, but every answer is a tap or a
// short input. NOT a free chatbot, NO AI persona. Ends WhatsApp-first,
// Shira-confirmed. No real calendar grid, no auto-booking, no prices.

const SVC_OPTS = [
  { id:'family',    label:'משפחה' },
  { id:'kids',      label:'ילדים' },
  { id:'oneyear',   label:'גיל שנה / סמאש קייק' },
  { id:'halake',    label:'חלאקה' },
  { id:'seasonal',  label:'פורים / סט עונתי' },
  { id:'outdoor',   label:'צילומי חוץ' },
  { id:'maternity', label:'הריון' },
];
const TIMING_OPTS = ['השבוע', 'החודש', 'חודש הבא', 'יש תאריך מיוחד'];
const TIME_OPTS = ['בוקר', 'צהריים', 'אחר הצהריים', 'גמיש'];

const DETAIL = {
  family:    { q:'כמה משתתפים תהיו בסשן?', mode:'chips', options:['2–3','4–5','6 ומעלה'], label:'משתתפים' },
  kids:      { q:'בן/בת כמה הילד/ה?', mode:'input', placeholder:'לדוגמה: שנתיים וחצי', label:'גיל הילד/ה' },
  oneyear:   { q:'בן/בת כמה הילד/ה?', mode:'input', placeholder:'לדוגמה: 11 חודשים', label:'גיל הילד/ה' },
  halake:    { q:'בן כמה הילד?', mode:'input', placeholder:'לדוגמה: 3 שנים', label:'גיל הילד' },
  seasonal:  { q:'כמה ילדים ישתתפו?', mode:'chips', options:['1','2','3','4 ומעלה'], label:'מספר ילדים' },
  outdoor:   { q:'כמה משתתפים תהיו?', mode:'chips', options:['2–3','4–5','6 ומעלה'], label:'משתתפים' },
  maternity: { q:'באיזה שבוע את?', mode:'input', placeholder:'לדוגמה: שבוע 30', label:'שבוע הריון' },
};

function svcName(id){ return (SERVICES.find(s => s.id === id) || {}).name || ''; }

function makeWindows(pref){
  const days = ['יום ראשון', 'יום שלישי', 'יום חמישי'];
  const byPref = {
    'בוקר':        ['10:00','09:30','11:30'],
    'צהריים':      ['12:30','13:00','12:00'],
    'אחר הצהריים': ['16:30','17:00','16:00'],
    'גמיש':        ['10:00','16:30','11:30'],
  };
  const times = byPref[pref] || byPref['גמיש'];
  return days.map((d,i) => ({ day:d, time:times[i] }));
}

function ConciergeChat({ open, initialService, onClose }){
  const [msgs, setMsgs] = React.useState([]);
  const [typing, setTyping] = React.useState(false);
  const [phase, setPhase] = React.useState('none');   // what the footer collects
  const [ans, setAns] = React.useState({});
  const [windows, setWindows] = React.useState([]);
  const [sel, setSel] = React.useState(-1);
  const [draft, setDraft] = React.useState('');
  const [nm, setNm] = React.useState('');
  const [ph, setPh] = React.useState('');
  const ansRef = React.useRef({});
  const timers = React.useRef([]);
  const bodyRef = React.useRef(null);

  const after = (ms, fn) => { const t = setTimeout(fn, ms); timers.current.push(t); };
  const clearTimers = () => { timers.current.forEach(clearTimeout); timers.current = []; };
  const pushStudio = (kind, content) => setMsgs(m => [...m, { from:'studio', kind, content, id:Math.random() }]);
  const pushUser = (text) => setMsgs(m => [...m, { from:'user', kind:'text', content:text, id:Math.random() }]);
  const setA = (patch) => { ansRef.current = { ...ansRef.current, ...patch }; setAns(a => ({ ...a, ...patch })); };

  React.useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [msgs, typing, phase]);

  React.useEffect(() => () => clearTimers(), []);

  // (re)start the conversation whenever opened
  React.useEffect(() => {
    if (!open) return;
    clearTimers();
    setMsgs([]); setTyping(false); setPhase('none'); setSel(-1);
    setDraft(''); setNm(''); setPh('');
    const svc = initialService || null;
    ansRef.current = svc ? { service:svc } : {};
    setAns(ansRef.current);

    after(250, () => {
      pushStudio('text', 'היי, כאן הסטודיו של פינק ליידי 🙂'.replace(' 🙂',''));
      after(900, () => {
        if (svc){
          pushStudio('text', 'נשמח לבדוק זמינות ל' + svcName(svc).replace('צילומי ','צילומי ') + '. כמה שאלות קצרות ונסיים.');
          askAfter(1100, 'timing');
        } else {
          pushStudio('text', 'נשמח לעזור לבדוק זמינות לסשן שלכם — כמה שאלות קצרות ונסיים.');
          askAfter(1100, 'service');
        }
      });
    });
  }, [open, initialService]);

  // show a typing beat, then the studio question for `next`, then open its input
  function askAfter(delay, next){
    after(delay, () => {
      setPhase('none'); setTyping(true);
      after(750, () => {
        setTyping(false);
        const a = ansRef.current;
        if (next === 'service')    pushStudio('text', 'איזה צילום מעניין אותך?');
        if (next === 'timing')     pushStudio('text', 'מתי בערך תרצו להגיע?');
        if (next === 'specialdate')pushStudio('text', 'מצוין. מהו התאריך המיוחד?');
        if (next === 'time')       pushStudio('text', 'ובאיזו שעה ביום נוח לכם?');
        if (next === 'detail')     pushStudio('text', DETAIL[a.service].q);
        if (next === 'contact')    pushStudio('text', 'כדי שנחזור אליכם לאישור — מה השם ומספר טלפון?');
        if (next === 'summary'){
          pushStudio('text', 'תודה! ריכזתי הכל. רוצים שאציע לכם כמה מועדים אפשריים?');
          pushStudio('summary', a);
        }
        if (next === 'checking'){
          pushStudio('checking', 'רגע, מכינה לכם כמה אפשרויות שיכולות להתאים…');
          after(2000, () => {
            const w = makeWindows(a.time);
            setWindows(w);
            setTyping(true);
            after(700, () => {
              setTyping(false);
              pushStudio('text', 'הנה כמה הצעות מועד שיכולות להתאים. שירה תאשר סופית מולכם:');
              pushStudio('windows', w);
              pushStudio('note', 'האישור הסופי נעשה בוואטסאפ מול שירה.');
              setPhase('results');
            });
          });
        }
        if (next === 'fallback'){
          pushStudio('text', 'לא מצאנו התאמה מושלמת, אבל שירה תבדוק ידנית ותציע לכם אפשרויות שמתאימות בדיוק.');
          setPhase('fallback');
        }
        if (next !== 'summary' && next !== 'checking' && next !== 'fallback') setPhase(next);
        if (next === 'summary') setPhase('summary');
      });
    });
  }

  // ---- answer handlers ----
  const pickService = (o) => { pushUser(o.label); setA({ service:o.id }); askAfter(200, 'timing'); };
  const pickTiming  = (v) => { pushUser(v); setA({ timing:v }); askAfter(200, v === 'יש תאריך מיוחד' ? 'specialdate' : 'time'); };
  const submitDate  = () => { if (!draft.trim()) return; pushUser(draft.trim()); setA({ specialDate:draft.trim() }); setDraft(''); askAfter(200, 'time'); };
  const pickTime    = (v) => { pushUser(v); setA({ time:v }); askAfter(200, 'detail'); };
  const pickDetailChip = (v) => { pushUser(v); setA({ detail:v }); askAfter(200, 'contact'); };
  const submitDetailInput = () => { if (!draft.trim()) return; pushUser(draft.trim()); setA({ detail:draft.trim() }); setDraft(''); askAfter(200, 'contact'); };
  const submitContact = () => {
    if (!nm.trim() || !ph.trim()) return;
    pushUser(nm.trim() + ' · ' + ph.trim());
    setA({ name:nm.trim(), phone:ph.trim() });
    askAfter(200, 'summary');
  };
  const confirmSummary = () => { pushUser('אפשר לבדוק זמינות'); askAfter(200, 'checking'); };
  const pickWindow = (i) => {
    setSel(i);
    const w = windows[i];
    pushUser(w.day + ' · ' + w.time);
    setA({ window:w });
    setPhase('none'); setTyping(true);
    after(750, () => { setTyping(false); pushStudio('text', 'מעולה. נשלח לשירה לאישור סופי, והיא תחזור אליכם בוואטסאפ.'); setPhase('send'); });
  };
  const noWindow = () => { pushUser('אף מועד לא מתאים לי'); setA({ window:null }); askAfter(200, 'fallback'); };

  // ---- compose WhatsApp message ----
  const buildMessage = (manual) => {
    const a = ansRef.current;
    let m = 'היי שירה, הגעתי דרך האתר ובדקתי זמינות.\n';
    if (a.service) m += 'צילום: ' + svcName(a.service) + '\n';
    if (a.timing)  m += 'מתי: ' + a.timing + (a.specialDate ? ' · ' + a.specialDate : '') + '\n';
    if (a.time)    m += 'שעה מועדפת: ' + a.time + '\n';
    if (a.service && a.detail) m += DETAIL[a.service].label + ': ' + a.detail + '\n';
    if (manual)    m += 'מבקש/ת בדיקה ידנית של זמינות.\n';
    else if (a.window) m += 'מועד מועדף: ' + a.window.day + ' · ' + a.window.time + '\n';
    if (a.name)    m += 'השם: ' + a.name + '\n';
    if (a.phone)   m += 'טלפון: ' + a.phone + '\n';
    m += 'נשמח לאישור סופי מולך.';
    return m.trim();
  };

  // ---- renderers ----
  const renderMsg = (msg) => {
    if (msg.kind === 'summary'){
      const a = msg.content;
      const rows = [
        ['צילום', svcName(a.service)],
        ['מתי', (a.timing || '') + (a.specialDate ? ' · ' + a.specialDate : '')],
        ['שעה', a.time || ''],
        [a.service ? DETAIL[a.service].label : 'פרט', a.detail || ''],
        ['שם', a.name || ''],
        ['טלפון', a.phone || ''],
      ].filter(r => r[1]);
      return (
        <div className="cc-card" key={msg.id}>
          {rows.map((r,i) => (
            <div className="sum-row" key={i}><span className="k">{r[0]}</span><span className="v">{r[1]}</span></div>
          ))}
        </div>
      );
    }
    if (msg.kind === 'windows'){
      return (
        <div className="cc-card" key={msg.id}>
          <div className="win-head">הצעות מועד · ממתינות לאישור שירה</div>
          {msg.content.map((w,i) => (
            <button key={i} className={'win' + (sel === i ? ' sel' : '')} onClick={() => phase === 'results' && pickWindow(i)}>
              <span className="dot">{sel === i ? Ic.check({ s:15, c:'#fbf6f1' }) : null}</span>
              <span className="win-txt"><span className="day">{w.day}</span><span className="tm">{w.time}</span></span>
            </button>
          ))}
        </div>
      );
    }
    if (msg.kind === 'note'){
      return <div className="cc-note" key={msg.id}><span className="ck">{Ic.check({ s:14 })}</span>{msg.content}</div>;
    }
    if (msg.kind === 'checking'){
      return (
        <div className="cc-msg" key={msg.id}>
          <div className="bubble studio" style={{ display:'flex', alignItems:'center', gap:10 }}>
            {Ic.clock({ s:18, c:'#9a655d' })}{msg.content}
          </div>
        </div>
      );
    }
    return (
      <div className="cc-msg" key={msg.id}>
        <div className={'bubble ' + msg.from}>{msg.content}</div>
      </div>
    );
  };

  // ---- footer composer per phase ----
  const detailCfg = ans.service ? DETAIL[ans.service] : null;
  const renderFoot = () => {
    if (phase === 'service')
      return <div className="cc-chips">{SVC_OPTS.map(o => <button key={o.id} className="cc-chip" onClick={() => pickService(o)}>{o.label}</button>)}</div>;
    if (phase === 'timing')
      return <div className="cc-chips">{TIMING_OPTS.map(v => <button key={v} className="cc-chip" onClick={() => pickTiming(v)}>{v}</button>)}</div>;
    if (phase === 'time')
      return <div className="cc-chips">{TIME_OPTS.map(v => <button key={v} className="cc-chip" onClick={() => pickTime(v)}>{v}</button>)}</div>;
    if (phase === 'specialdate')
      return (
        <div className="cc-inputrow">
          <div className="field"><input value={draft} onChange={e => setDraft(e.target.value)}
            placeholder="לדוגמה: יום הולדת ב-12.6" onKeyDown={e => e.key === 'Enter' && submitDate()} /></div>
          <button className="cc-send" onClick={submitDate} disabled={!draft.trim()}>{Ic.arrowL({ s:18, c:'#f5f0e8' })}</button>
        </div>
      );
    if (phase === 'detail' && detailCfg && detailCfg.mode === 'chips')
      return <div className="cc-chips">{detailCfg.options.map(v => <button key={v} className="cc-chip" onClick={() => pickDetailChip(v)}>{v}</button>)}</div>;
    if (phase === 'detail' && detailCfg)
      return (
        <div className="cc-inputrow">
          <div className="field"><input value={draft} onChange={e => setDraft(e.target.value)}
            placeholder={detailCfg.placeholder} onKeyDown={e => e.key === 'Enter' && submitDetailInput()} /></div>
          <button className="cc-send" onClick={submitDetailInput} disabled={!draft.trim()}>{Ic.arrowL({ s:18, c:'#f5f0e8' })}</button>
        </div>
      );
    if (phase === 'contact')
      return (
        <React.Fragment>
          <div className="field" style={{ marginBottom:9 }}><input value={nm} onChange={e => setNm(e.target.value)} placeholder="השם שלך" /></div>
          <div className="cc-inputrow">
            <div className="field"><input value={ph} onChange={e => setPh(e.target.value)} type="tel" placeholder="טלפון לחזרה" dir="ltr" style={{ textAlign:'right' }} /></div>
            <button className="cc-send" onClick={submitContact} disabled={!nm.trim() || !ph.trim()}>{Ic.arrowL({ s:18, c:'#f5f0e8' })}</button>
          </div>
        </React.Fragment>
      );
    if (phase === 'summary')
      return <button className="btn btn-rose" onClick={confirmSummary}>{Ic.clock({ s:18, c:'#fbf6f1' })} בדיקת זמינות</button>;
    if (phase === 'results')
      return (
        <React.Fragment>
          <div className="cc-hint">בחרו את המועד שמתאים לכם</div>
          <button className="cc-fallback-link" onClick={noWindow}>אף מועד לא מתאים לי</button>
        </React.Fragment>
      );
    if (phase === 'send')
      return (
        <a className="btn btn-rose" href={waLink(buildMessage(false))} target="_blank" rel="noopener"
          style={{ textDecoration:'none' }} onClick={() => after(500, onClose)}>
          {Ic.chat({ s:18, c:'#fbf6f1' })} שליחה לוואטסאפ לאישור מול שירה
        </a>
      );
    if (phase === 'fallback')
      return (
        <a className="btn btn-rose" href={waLink(buildMessage(true))} target="_blank" rel="noopener"
          style={{ textDecoration:'none' }} onClick={() => after(500, onClose)}>
          {Ic.chat({ s:18, c:'#fbf6f1' })} שליחה לוואטסאפ לבדיקה ידנית
        </a>
      );
    return <div className="cc-hint">רגע…</div>;
  };

  return (
    <div className={'cc' + (open ? ' open' : '')}>
      <div className="cc-panel">
        <div className="cc-head">
          <div className="cc-mono">פל</div>
          <div className="cc-id">
            <div className="nm">פינק ליידי</div>
            <div className="st"><span className="live"></span>בדיקת זמינות · מענה אישי של שירה</div>
          </div>
          <button className="cc-x" onClick={onClose} aria-label="סגירה">{Ic.close({ s:22 })}</button>
        </div>

        <div className="cc-body" ref={bodyRef}>
          {msgs.map(renderMsg)}
          {typing && (
            <div className="cc-msg"><div className="bubble studio typing"><span></span><span></span><span></span></div></div>
          )}
        </div>

        <div className="cc-foot">{renderFoot()}</div>
      </div>
    </div>
  );
}
Object.assign(window, { ConciergeChat });
