// inb-data.jsx — mock Inbox data + i18n

(() => {
  const NOW = new Date(2026, 4, 26, 14, 30);
  const ago = (mins) => new Date(NOW.getTime() - mins * 60000);
  const daysAgo = (days, hour = 12, min = 0) => new Date(2026, 4, 26 - days, hour, min);

  const initials = (name) => (name || '?').split(/\s+/).filter(Boolean).slice(0, 2).map((p) => p[0]).join('').toUpperCase();
  const avColor = (seed) => {
    const colors = ['#0d9488', '#2563eb', '#9333ea', '#db2777', '#ea580c', '#16a34a', '#64748b'];
    const sum = String(seed || '').split('').reduce((s, ch) => s + ch.charCodeAt(0), 0);
    return colors[sum % colors.length];
  };
  const maskName = (name) => initials(name).split('').join('. ') + '.';
  const fmtTime = (d) => d.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });
  const fmtRelative = (d, lang = 'ru') => {
    const diff = Math.max(1, Math.round((NOW - d) / 60000));
    if (diff < 60) return lang === 'ru' ? `${diff} мин назад` : `${diff}m ago`;
    if (diff < 1440) {
      const h = Math.floor(diff / 60);
      const m = diff % 60;
      return lang === 'ru' ? `${h}ч ${m ? `${m}м ` : ''}назад` : `${h}h ${m ? `${m}m ` : ''}ago`;
    }
    const days = Math.floor(diff / 1440);
    return lang === 'ru' ? `${days} дн назад` : `${days}d ago`;
  };
  const fmtDayLabel = (d, lang = 'ru') => {
    const a = new Date(d); a.setHours(0, 0, 0, 0);
    const b = new Date(NOW); b.setHours(0, 0, 0, 0);
    const diff = Math.round((b - a) / 86400000);
    if (diff === 0) return lang === 'ru' ? 'Сегодня' : 'Today';
    if (diff === 1) return lang === 'ru' ? 'Вчера' : 'Yesterday';
    return d.toLocaleDateString(lang === 'ru' ? 'ru-RU' : 'en-US', { day: 'numeric', month: 'short' });
  };

  const msg = (id, from, mins, text, mgr) => ({ id, from, at: ago(mins), text, mgr });
  const compliancePass = [
    { rule: 'Greeting by standard', pass: true, note: 'Тон соответствует стандарту' },
    { rule: 'Offer matched to guest need', pass: true, note: 'Ответ связан с датами и домиком' },
    { rule: 'Response under SLA', pass: true, note: 'Первый ответ быстрее 30 минут' },
    { rule: 'Clear next step', pass: true, note: 'Есть конкретный следующий шаг' },
    { rule: 'No prohibited promise', pass: true, note: 'Нет неподтвержденных обещаний' },
  ];

  const conv = (cfg) => ({
    status: 'open',
    flagged: false,
    unread: false,
    online: false,
    inHouse: false,
    assignedTo: 'Anna',
    ...cfg,
  });

  const CONVERSATIONS = [
    conv({
      id: 'c01', channel: 'whatsapp',
      guest: { name: 'Иванов Александр', handle: '+371 24 555 111', segment: 'Champion', linkedGuestId: 'g-1001', ltv: 2480, visits: 7, country: 'LV', lang: 'ru' },
      booking: { id: 'B-2856', cabin: 'Bali', dates: '26–28 мая', state: 'in-house', daysOut: 0 },
      unread: true, online: true, inHouse: true, lastInbound: ago(24),
      messages: [
        msg('m01-1', 'guest', 78, 'Добрый день! Можно сегодня забронировать SPA на 17:00?'),
        msg('m01-2', 'manager', 60, 'Здравствуйте, Александр! Да, есть слот на 17:00 для SPA. Подтвердить для двух гостей?', 'Anna'),
        msg('m01-3', 'guest', 35, 'Да, подтвердите пожалуйста. И можно еще меню ресторана?'),
        msg('m01-4', 'manager', 18, 'Готово, SPA подтверждено. Меню ресторана отправлю следующим сообщением.', 'Anna'),
      ],
      analytics: {
        firstResponseMin: 18, totalMin: 60, sentiment: 'positive', sentimentTrend: [0.62,0.7,0.78,0.82,0.86],
        compliance: { score: 5, total: 5, items: compliancePass },
        suggestions: [
          { id: 's1', text: 'Предложить ужин в Restaurant после SPA', insertable: true, snippet: 'Также можем забронировать для вас столик в Restaurant после SPA. Хотите на 19:00?' },
          { id: 's2', text: 'Отметить preference: SPA evening slot', insertable: false },
          { id: 's3', text: 'Проверить late checkout для Champion guest', insertable: false },
        ],
      },
    }),
    conv({
      id: 'c02', channel: 'instagram',
      guest: { name: 'Sara Ahmed', handle: '@sara.ahmed_swe', segment: 'Unknown', linkedGuestId: null, ltv: 0, visits: 0, country: 'SE', lang: 'en' },
      booking: null, assignedTo: null, unread: true, lastInbound: ago(47),
      messages: [
        msg('m02-1', 'guest', 95, 'Hi! Do you have a free guesthouse for 2 adults in June?'),
        msg('m02-2', 'manager', 71, 'Hi Sara! Which dates are you considering?', 'Maria'),
        msg('m02-3', 'guest', 47, 'June 14-16. Is SPA included?'),
      ],
      analytics: {
        firstResponseMin: 24, totalMin: 48, sentiment: 'neutral', sentimentTrend: [0.5,0.55,0.58,0.6],
        compliance: { score: 4, total: 5, items: [...compliancePass.slice(0, 3), { rule: 'Ask for booking details', pass: false, msg: 'm02-2', note: 'Не уточнен бюджет / количество гостей' }, compliancePass[4]] },
        suggestions: [{ id: 's1', text: 'Send June availability and SPA package', insertable: true, snippet: 'For June 14-16 we can offer Cyprus or Latvia. SPA is booked separately, but I can suggest a package.' }],
      },
    }),
    conv({
      id: 'c03', channel: 'messenger',
      guest: { name: 'Orlova Marina', handle: 'Marina Orlova', segment: 'Loyal', linkedGuestId: 'g-1003', ltv: 1320, visits: 3, country: 'LV', lang: 'ru' },
      booking: { id: 'B-2862', cabin: 'Maldives', dates: '29–31 мая', state: 'confirmed', daysOut: 3 },
      assignedTo: 'Diana', flagged: true, lastInbound: ago(132),
      messages: [msg('m03-1','guest',190,'Можно добавить детскую кроватку?'), msg('m03-2','manager',156,'Да, добавили в бронь.', 'Diana'), msg('m03-3','guest',132,'Спасибо!')],
      analytics: { firstResponseMin: 34, totalMin: 58, sentiment: 'positive', sentimentTrend: [0.52,0.6,0.72], compliance: { score: 4, total: 5, items: compliancePass.map((x,i)=> i===2 ? { ...x, pass:false, msg:'m03-2', note:'Ответ чуть выше SLA' } : x) }, suggestions: [{ id:'s1', text:'Send pre-arrival message tomorrow', insertable:false }] },
    }),
    conv({
      id: 'c04', channel: 'whatsapp',
      guest: { name: 'Romano Luca', handle: '+39 333 112233', segment: 'At risk', linkedGuestId: 'g-1004', ltv: 760, visits: 1, country: 'IT', lang: 'en' },
      booking: { id: 'B-2848', cabin: 'Portofino', dates: '25–27 мая', state: 'in-house', daysOut: 0 },
      assignedTo: 'Ivan', unread: true, lastInbound: ago(168),
      messages: [msg('m04-1','guest',230,'The WiFi quality in Portofino is very poor.'), msg('m04-2','manager',210,'We are sorry, checking it now.', 'Ivan'), msg('m04-3','guest',168,'Still not working well.')],
      analytics: { firstResponseMin: 20, totalMin: 62, sentiment: 'negative', sentimentTrend: [0.48,0.34,0.25], compliance: { score: 3, total: 5, items: [compliancePass[0], { rule:'Own the issue', pass:false, msg:'m04-2', note:'Нужно дать ETA и компенсационный жест' }, compliancePass[2], { rule:'Follow-up confirmation', pass:false, msg:'m04-3', note:'Нет финального follow-up' }, compliancePass[4]] }, suggestions: [{ id:'s1', text:'Send clear ETA and compensation', insertable:true, snippet:'Luca, sorry again. Our technician is checking WiFi now; I will update you within 20 minutes. We can also offer complimentary SPA access for the inconvenience.' }] },
    }),
    conv({ id:'c05', channel:'instagram', guest:{ name:'Katrina Melnik', handle:'@katrina_weekend', segment:'New', linkedGuestId:'g-1005', ltv:420, visits:1, country:'EE', lang:'ru' }, booking:{ id:'B-2866', cabin:'Cyprus', dates:'1–3 июня', state:'confirmed', daysOut:6 }, assignedTo:'Maria', lastInbound:ago(12), messages:[msg('m05-1','guest',40,'Есть ли свободный столик в Restaurant на пятницу?'), msg('m05-2','manager',12,'Проверяю и вернусь с подтверждением.', 'Maria')], analytics:{ firstResponseMin:28,totalMin:28,sentiment:'neutral',sentimentTrend:[0.5,0.57],compliance:{score:5,total:5,items:compliancePass},suggestions:[{id:'s1',text:'Confirm table and ask time',insertable:true,snippet:'Да, можем забронировать столик. На какое время вам удобно?'}] } }),
    conv({ id:'c06', channel:'whatsapp', guest:{ name:'Petrova Elena', handle:'+371 22 900 332', segment:'Promising', linkedGuestId:'g-1006', ltv:980, visits:2, country:'LV', lang:'ru' }, booking:{ id:'B-2860', cabin:'Latvia', dates:'27–29 мая', state:'confirmed', daysOut:1 }, assignedTo:'Anna', lastInbound:ago(74), messages:[msg('m06-1','guest',122,'Можно приехать на час раньше?'), msg('m06-2','manager',74,'Да, ранний заезд возможен с 14:00.', 'Anna')], analytics:{ firstResponseMin:48,totalMin:48,sentiment:'positive',sentimentTrend:[0.55,0.64],compliance:{score:4,total:5,items:compliancePass.map((x,i)=> i===2 ? {...x,pass:false,msg:'m06-2',note:'SLA выше 30 минут'} : x)},suggestions:[] } }),
    conv({ id:'c07', channel:'messenger', guest:{ name:'Nikolai Berg', handle:'Nikolai B.', segment:'New', linkedGuestId:'g-1007', ltv:310, visits:1, country:'DE', lang:'en' }, booking:null, assignedTo:null, unread:true, lastInbound:ago(16), messages:[msg('m07-1','guest',16,'Can I bring a dog?')], analytics:{ firstResponseMin:null,totalMin:16,sentiment:'neutral',sentimentTrend:[0.5],compliance:{score:0,total:5,items:[]},suggestions:[{id:'s1',text:'Pet policy reply',insertable:true,snippet:'Yes, dogs are welcome in selected guesthouses. Please tell us the dog size and your dates.'}] } }),
    conv({ id:'c08', channel:'instagram', status:'spam', guest:{ name:'Booking manager', handle:'@promo_booking_fast', segment:'Spam', linkedGuestId:null, ltv:0, visits:0, country:'--', lang:'en' }, booking:null, assignedTo:null, lastInbound:ago(300), messages:[msg('m08-1','guest',300,'Promote your hotel with 10000 followers cheap!!!')], analytics:{ firstResponseMin:null,totalMin:0,sentiment:'negative',sentimentTrend:[0.1],compliance:{score:0,total:0,items:[]},suggestions:[] } }),
    conv({ id:'c09', channel:'whatsapp', guest:{ name:'Sidorov Kirill', handle:'+371 29 001 777', segment:'Repeat', linkedGuestId:'g-1009', ltv:1510, visits:4, country:'LV', lang:'ru' }, booking:{ id:'B-2868', cabin:'Bali', dates:'5–7 июня', state:'confirmed', daysOut:10 }, assignedTo:'Diana', flagged:true, lastInbound:ago(188), messages:[msg('m09-1','guest',220,'Хочу повторить прошлый пакет с массажем.'), msg('m09-2','manager',188,'Конечно, проверю доступность SPA.', 'Diana')], analytics:{ firstResponseMin:32,totalMin:32,sentiment:'positive',sentimentTrend:[0.7,0.74],compliance:{score:4,total:5,items:compliancePass.map((x,i)=> i===2 ? {...x,pass:false,msg:'m09-2',note:'SLA слегка выше'} : x)},suggestions:[{id:'s1',text:'Offer same package + Restaurant',insertable:true,snippet:'Можем повторить прошлый SPA-пакет и добавить ужин в Restaurant. Подтвердить?'}] } }),
    conv({ id:'c10', channel:'instagram', guest:{ name:'Laura Tamm', handle:'@laura_tamm', segment:'New', linkedGuestId:null, ltv:0, visits:0, country:'EE', lang:'en' }, booking:null, assignedTo:'Maria', unread:true, lastInbound:ago(98), messages:[msg('m10-1','guest',98,'Do you have gift cards?')], analytics:{ firstResponseMin:null,totalMin:98,sentiment:'neutral',sentimentTrend:[0.5],compliance:{score:0,total:5,items:[]},suggestions:[{id:'s1',text:'Gift card answer',insertable:true,snippet:'Yes, we have gift cards for stays, SPA and Restaurant. What amount would you like?'}] } }),
    conv({ id:'c11', channel:'whatsapp', guest:{ name:'Berg Henrik', handle:'+46 70 111 222', segment:'High value', linkedGuestId:'g-1011', ltv:3100, visits:5, country:'SE', lang:'en' }, booking:{ id:'B-2828', cabin:'Maldives', dates:'18–21 мая', state:'checked-out', daysOut:-5 }, assignedTo:'Anna', unread:true, flagged:true, lastInbound:ago(3600), messages:[msg('m11-1','guest',3700,'We forgot a charger in Maldives. Can you check?'), msg('m11-2','manager',3640,'I will ask housekeeping.', 'Anna'), msg('m11-3','guest',3600,'Any update?')], analytics:{ firstResponseMin:60,totalMin:100,sentiment:'negative',sentimentTrend:[0.45,0.34,0.28],compliance:{score:2,total:5,items:[compliancePass[0],{rule:'Follow up promised action',pass:false,msg:'m11-2',note:'Нет follow-up после обещания'},{rule:'SLA for high-value guest',pass:false,msg:'m11-3',note:'>24h без ответа'},compliancePass[3],compliancePass[4]]},suggestions:[{id:'s1',text:'Recover service failure',insertable:true,snippet:'Henrik, sorry for the delay. I am checking with housekeeping now and will update you in 15 minutes.'}] } }),
    conv({ id:'c12', channel:'messenger', guest:{ name:'Anna Petrova', handle:'Anna P.', segment:'Loyal', linkedGuestId:'g-1012', ltv:1700, visits:4, country:'LV', lang:'ru' }, booking:{ id:'B-2872', cabin:'Cyprus', dates:'8–10 июня', state:'confirmed', daysOut:13 }, assignedTo:'Diana', lastInbound:ago(240), messages:[msg('m12-1','guest',270,'Можно оплатить оставшуюся часть при заезде?'), msg('m12-2','manager',240,'Да, возможно. Я отмечу в брони.', 'Diana')], analytics:{ firstResponseMin:30,totalMin:30,sentiment:'positive',sentimentTrend:[0.57,0.67],compliance:{score:5,total:5,items:compliancePass},suggestions:[] } }),
    conv({ id:'c13', channel:'instagram', guest:{ name:'Marta Ozola', handle:'@marta.oz', segment:'New', linkedGuestId:null, ltv:0, visits:0, country:'LV', lang:'ru' }, booking:null, assignedTo:null, lastInbound:ago(420), messages:[msg('m13-1','guest',420,'Сколько стоит романтический пакет?')], analytics:{ firstResponseMin:null,totalMin:420,sentiment:'neutral',sentimentTrend:[0.5],compliance:{score:0,total:5,items:[]},suggestions:[{id:'s1',text:'Romantic package reply',insertable:true,snippet:'Романтический пакет можно добавить к Guesthouses: SPA, ужин в Restaurant и welcome set. Напишите даты, и я проверю доступность.'}] } }),
    conv({ id:'c14', channel:'whatsapp', guest:{ name:'Timo Laine', handle:'+358 40 555 019', segment:'Repeat', linkedGuestId:'g-1014', ltv:1180, visits:2, country:'FI', lang:'en' }, booking:{ id:'B-2875', cabin:'Portofino', dates:'11–13 июня', state:'confirmed', daysOut:16 }, assignedTo:'Ivan', lastInbound:ago(55), messages:[msg('m14-1','guest',80,'Can you send invoice?'), msg('m14-2','manager',55,'Sure, I will send it shortly.', 'Ivan')], analytics:{ firstResponseMin:25,totalMin:25,sentiment:'neutral',sentimentTrend:[0.52,0.55],compliance:{score:5,total:5,items:compliancePass},suggestions:[] } }),
    conv({ id:'c15', channel:'messenger', guest:{ name:'Greta Kalnina', handle:'Greta K.', segment:'Promising', linkedGuestId:'g-1015', ltv:690, visits:2, country:'LV', lang:'ru' }, booking:null, assignedTo:'Maria', lastInbound:ago(8), messages:[msg('m15-1','guest',8,'Есть свободно на эти выходные?')], analytics:{ firstResponseMin:null,totalMin:8,sentiment:'positive',sentimentTrend:[0.7],compliance:{score:0,total:5,items:[]},suggestions:[{id:'s1',text:'Weekend availability',insertable:true,snippet:'Да, проверяю доступность Guesthouses на эти выходные. Сколько гостей планируется?'}] } }),
  ];

  const analytics = {
    kpis: [
      ['Avg first response', '34m', '-8m', 'pos'],
      ['Avg resolution', '3h 12m', '+14m', 'flat'],
      ['Today', '43', '+9', 'pos'],
      ['Unresolved', '11', '+3', 'warn'],
      ['Conversion', '28%', '+4 п.п.', 'pos'],
      ['Compliance', '84%', '+6 п.п.', 'pos'],
      ['Sentiment+', '61%', '+5 п.п.', 'pos'],
      ['Templates used', '37%', '+11%', 'pos'],
    ],
    managers: [
      { name: 'Anna', conversations: 18, first: '22m', compliance: 91, conversion: 34, tone: 'pos' },
      { name: 'Maria', conversations: 16, first: '39m', compliance: 82, conversion: 24, tone: 'warn' },
      { name: 'Diana', conversations: 11, first: '28m', compliance: 88, conversion: 29, tone: 'pos' },
      { name: 'Ivan', conversations: 9, first: '46m', compliance: 74, conversion: 18, tone: 'warn' },
    ],
    channels: [{ name: 'WhatsApp', value: 48 }, { name: 'Instagram', value: 34 }, { name: 'Messenger', value: 18 }],
    types: [{ name: 'Booking', value: 42 }, { name: 'Service', value: 24 }, { name: 'SPA', value: 18 }, { name: 'Restaurant', value: 9 }, { name: 'Other', value: 7 }],
    topics: [
      ['Availability', 41], ['SPA packages', 32], ['Restaurant booking', 28], ['Early check-in', 23], ['WiFi quality', 18, true],
      ['Payment', 16], ['Pets', 14], ['Gift cards', 12], ['Lost items', 9], ['Transport', 8], ['Invoice', 7], ['Romantic package', 6],
      ['Late checkout', 5], ['Kids setup', 4], ['Cancellation', 3],
    ],
    violations: [['Follow-up promised action', 7], ['SLA > 2h', 5], ['No clear next step', 4], ['Missing personalization', 3], ['No recovery gesture', 2]],
    trends: { response: [46,42,37,36,33,31,34], compliance: [76,78,81,80,84,86,84], resolved: [18,20,21,19,24,26,25] },
  };

  const I18N = {
    ru: {
      title: 'Inbox',
      tabs: { conversations: 'Разговоры', analytics: 'Аналитика' },
      filters: { all: 'Все', unread: 'Непрочитанные', unassigned: 'Без исполнителя', mine: '@Я', flagged: 'Помечено', bookings: 'С бронями', spam: 'Спам' },
      sort: { oldest: 'Старые без ответа', newest: 'Новые', priority: 'По приоритету', ltv: 'По LTV' },
      search: 'Поиск по имени, handle, сообщению',
      noSelection: 'Выберите разговор',
      noSelectionSub: 'Слева список входящих сообщений по всем каналам.',
      composer: 'Напишите ответ...',
      send: 'Send',
      outWindow: 'Последнее входящее сообщение старше 24 часов. Для WhatsApp может потребоваться template message.',
      sendingAs: 'Sending as SEOVILLAGE {channel} to {handle}',
      customer: 'Customer',
      noGuest: 'No guest linked',
      linkGuest: 'Link to guest',
      createGuest: 'Create new guest',
      analytics: 'Conv-аналитика',
      firstResponse: 'First response',
      duration: 'Duration',
      sentiment: 'Sentiment',
      standards: 'Standards check',
      suggestions: 'Suggestions',
      actions: 'Actions',
      openProfile: 'Open full profile →',
      insert: 'Insert',
      actionButtons: ['Assign', 'Mark resolved', 'Mute', 'Create booking', 'Add note'],
      emptyList: 'Нет разговоров по выбранным фильтрам',
    },
    en: {
      title: 'Inbox',
      tabs: { conversations: 'Conversations', analytics: 'Analytics' },
      filters: { all: 'All', unread: 'Unread', unassigned: 'Unassigned', mine: '@Me', flagged: 'Flagged', bookings: 'With bookings', spam: 'Spam' },
      sort: { oldest: 'Oldest unanswered', newest: 'Newest', priority: 'By priority', ltv: 'By LTV' },
      search: 'Search name, handle, message',
      noSelection: 'Select a conversation',
      noSelectionSub: 'Incoming messages from all channels are on the left.',
      composer: 'Write a reply...',
      send: 'Send',
      outWindow: 'Last inbound message is older than 24h. WhatsApp may require a template message.',
      sendingAs: 'Sending as SEOVILLAGE {channel} to {handle}',
      customer: 'Customer',
      noGuest: 'No guest linked',
      linkGuest: 'Link to guest',
      createGuest: 'Create new guest',
      analytics: 'Conv analytics',
      firstResponse: 'First response',
      duration: 'Duration',
      sentiment: 'Sentiment',
      standards: 'Standards check',
      suggestions: 'Suggestions',
      actions: 'Actions',
      openProfile: 'Open full profile →',
      insert: 'Insert',
      actionButtons: ['Assign', 'Mark resolved', 'Mute', 'Create booking', 'Add note'],
      emptyList: 'No conversations for selected filters',
    },
  };

  window.INB = { NOW, CONVERSATIONS, ANALYTICS: analytics, initials, avColor, maskName, fmtTime, fmtRelative, fmtDayLabel };
  window.INBOX_I18N = I18N;
})();
