import { storage } from "./storage";

export const MESSAGE_TEMPLATES = [
  {
    id: "formal",
    name: "رسمي",
    template: `🌟 *دعوة خاصة* 🌟\n\nعزيزنا *{name}*،\n\nنتشرف بدعوتكم لمناسبتنا الخاصة.\n\nتأكيد الحضور:\n🔗 {link}\n\nننتظركم بكل سرور 🤍`,
  },
  {
    id: "friendly",
    name: "ودّي",
    template: `أهلاً *{name}* 💜\n\nيسعدنا دعوتك لمناسبتنا الخاصة!\n\nشرّفنا بحضورك وأكّد من هنا:\n🔗 {link}\n\nبانتظارك! 🤍`,
  },
  {
    id: "short",
    name: "مختصر",
    template: `*{name}*، أنت مدعو/ة لمناسبتنا 🎉\n\nللتفاصيل وتأكيد الحضور:\n🔗 {link}`,
  },
  {
    id: "traditional",
    name: "تقليدي",
    template: `بسم الله الرحمن الرحيم\n\nعزيزنا/عزيزتنا *{name}*\n\nيسرّنا ويشرّفنا دعوتكم لحضور مناسبتنا.\n\nنأمل تأكيد تشريفكم عبر الرابط:\n🔗 {link}\n\nوالله يحفظكم ويبارك فيكم 🤲`,
  },
];

export const REMINDER_TEMPLATES = [
  {
    id: "formal_reminder",
    name: "رسمي",
    template: `عزيزنا {name}،\n\nنذكّركم بأن مناسبتنا اقتربت، ونأمل تشريفنا بحضوركم الكريم.\n\nشكراً لاهتمامكم 🤍`,
  },
  {
    id: "friendly_reminder",
    name: "ودّي",
    template: `أهلاً {name}! 🌟\n\nبس أذكّرك إن مناسبتنا اقتربت!\nبانتظار حضورك وما يكمل الفرح إلا بيك 💜`,
  },
];

const INVISIBLE_CHARS = ['\u200B', '\u200C', '\uFEFF'];

function addInvisibleVariation(text: string): string {
  const lines = text.split('\n');
  return lines.map(line => {
    if (!line.trim() || line.includes('http') || line.startsWith('🔗') || line.startsWith('📅') || line.startsWith('⏰') || line.startsWith('📍') || line.startsWith('✍')) return line;
    const words = line.split(' ');
    if (words.length < 2) return line;
    const numInserts = Math.floor(Math.random() * 2) + 1;
    const positions = new Set<number>();
    while (positions.size < Math.min(numInserts, words.length - 1)) {
      positions.add(Math.floor(Math.random() * (words.length - 1)));
    }
    return words.map((w, i) =>
      positions.has(i) ? w + INVISIBLE_CHARS[Math.floor(Math.random() * INVISIBLE_CHARS.length)] : w
    ).join(' ');
  }).join('\n');
}

const DETAIL_ORDERINGS = [
  ['date', 'time', 'venue'],
  ['venue', 'date', 'time'],
  ['time', 'venue', 'date'],
];

function formatTime12hAr(time: string): string {
  const [hStr, mStr] = time.split(":");
  let h = parseInt(hStr, 10);
  const m = mStr || "00";
  const suffix = h < 12 ? "ص" : "م";
  h = h % 12 || 12;
  return `${h}:${m} ${suffix}`;
}

async function buildEventDetailsBlock(userId: number, fixed = false): Promise<string> {
  const details = await storage.getEventDetails(userId);
  if (!details) return "";
  const lineMap: Record<string, string> = {};
  const dateLabel = fixed ? 'التاريخ' : (Math.random() < 0.5 ? 'التاريخ' : 'الموعد');
  const timeLabel = fixed ? 'الوقت' : (Math.random() < 0.5 ? 'الوقت' : 'التوقيت');
  const venueLabel = fixed ? 'المكان' : (Math.random() < 0.5 ? 'المكان' : 'الموقع');
  if (details.event_date) lineMap['date'] = `📅 ${dateLabel}: *${details.event_date}*`;
  if (details.event_time) lineMap['time'] = `⏰ ${timeLabel}: *${formatTime12hAr(details.event_time)}*`;
  if (details.event_venue_name) lineMap['venue'] = `📍 ${venueLabel}: *${details.event_venue_name}*`;
  if (Object.keys(lineMap).length === 0) return "";
  const ordering = fixed ? ['date', 'time', 'venue'] : DETAIL_ORDERINGS[Math.floor(Math.random() * DETAIL_ORDERINGS.length)];
  const lines = ordering.filter(k => lineMap[k]).map(k => lineMap[k]);
  return "\n\n" + lines.join("\n");
}

export function buildMessageFromTemplate(templateText: string, guestName: string, inviteLink: string, sender?: string, occasion?: string): string {
  return templateText
    .replace(/\{name\}/g, guestName)
    .replace(/\{link\}/g, inviteLink)
    .replace(/\{sender\}/g, sender || "")
    .replace(/\{occasion\}/g, occasion || "");
}

// userId = shared data owner (guests, event details, quota)
// settingsUserId = personal settings owner (template text, media, WhatsApp account)
// When settingsUserId is omitted it defaults to userId (single-user or primary-user context)
export async function buildMessage(templateId: string, userId: number, guestName: string, inviteLink: string, fixed = false, settingsUserId?: number, personalUserId?: number): Promise<string> {
  const suid = settingsUserId ?? userId;
  const puid = personalUserId ?? userId;
  const sharedDetails = await storage.getEventDetails(userId);
  // Merge personal fields (sender, occasion) from the session/personal user if different
  let details = sharedDetails;
  if (puid !== userId) {
    const personalDetails = await storage.getEventDetails(puid);
    const PERSONAL_FIELDS = ["event_sender", "event_occasion"];
    details = { ...(sharedDetails || {}) };
    for (const field of PERSONAL_FIELDS) {
      if (personalDetails?.[field] !== undefined) {
        (details as Record<string, string>)[field] = (personalDetails as Record<string, string>)[field];
      } else {
        delete (details as Record<string, string>)[field];
      }
    }
  }
  const sender = (details as Record<string, string>)?.event_sender || "";
  const occasion = (details as Record<string, string>)?.event_occasion || "";

  let msg: string;
  if (templateId === "custom" || templateId === "custom2") {
    const suffix = templateId === "custom2" ? "_2" : "";
    const beforeName = await storage.getSetting(suid, `custom_msg_before_name${suffix}`) || "";
    const between = await storage.getSetting(suid, `custom_msg_between${suffix}`) || "";
    const afterLink = await storage.getSetting(suid, `custom_msg_after_link${suffix}`) || "";
    if (between.trim()) {
      const betweenReplaced = between
        .replace(/\{sender\}/g, sender)
        .replace(/\{occasion\}/g, occasion)
        .replace(/\{name\}/g, guestName);
      const beforeReplaced = beforeName
        .replace(/\{sender\}/g, sender)
        .replace(/\{occasion\}/g, occasion)
        .replace(/\{name\}/g, guestName);
      const afterReplaced = afterLink
        .replace(/\{sender\}/g, sender)
        .replace(/\{occasion\}/g, occasion)
        .replace(/\{name\}/g, guestName);
      msg = (beforeReplaced ? beforeReplaced + "\n" : "") + `*${guestName}*` + "\n" + betweenReplaced + "\n" + inviteLink + (afterReplaced ? "\n" + afterReplaced : "");
    } else {
      const tmpl = MESSAGE_TEMPLATES.find(t => t.id === "formal") || MESSAGE_TEMPLATES[0];
      msg = buildMessageFromTemplate(tmpl.template, guestName, inviteLink, sender, occasion);
    }
  } else {
    const tmpl = MESSAGE_TEMPLATES.find(t => t.id === templateId) || MESSAGE_TEMPLATES[0];
    let builtMsg = buildMessageFromTemplate(tmpl.template, guestName, inviteLink, sender, occasion);
    msg = builtMsg;
  }

  // Build من/إلى header
  const headerLines: string[] = [];
  if (occasion) headerLines.push(`*${occasion}*`);
  if (sender) headerLines.push(`من: *${sender}*`);
  headerLines.push(`إلى: *${guestName}*`);
  const header = headerLines.join('\n') + '\n\n';
  msg = header + msg;

  if (!fixed) msg = addInvisibleVariation(msg);
  const eventBlock = await buildEventDetailsBlock(userId, fixed);
  const promoEnabled = await storage.getSetting(suid, "promo_footer_enabled");
  const promoFooter = promoEnabled === "true" ? "\n\n_إنفايتنا 💌_" : "";
  const user = await storage.getUser(userId);
  const footerSourceId = user?.parentHallId || userId;
  const customFooter = await storage.getSetting(footerSourceId, "custom_footer");
  const customFooterEnabled = await storage.getSetting(footerSourceId, "custom_footer_enabled");
  const isCustomFooterEnabled = customFooterEnabled !== "false";
  const customFooterBlock = (customFooter && customFooter.trim() && isCustomFooterEnabled) ? `\n\n${customFooter.trim()}` : "";
  return msg + eventBlock + customFooterBlock + promoFooter;
}

export async function buildReminderMessage(templateId: string, userId: number, guestName: string): Promise<string> {
  let msg: string;
  if (templateId === "custom_reminder") {
    const customMsg = await storage.getSetting(userId, "reminder_custom_msg") || "";
    if (customMsg.trim()) {
      msg = `${guestName}،\n\n${customMsg}`;
    } else {
      const tmpl = REMINDER_TEMPLATES[0];
      msg = tmpl.template.replace(/\{name\}/g, guestName);
    }
  } else {
    const tmpl = REMINDER_TEMPLATES.find(t => t.id === templateId) || REMINDER_TEMPLATES[0];
    msg = tmpl.template.replace(/\{name\}/g, guestName);
  }
  const eventBlock = await buildEventDetailsBlock(userId);
  return msg + eventBlock;
}
