// Mock data for Nordicrew T-Shirt Designer

// Stickers come from logos.jsx (BUILT_IN_STICKERS, loaded from stickers/ folder).
// Keep NORDICREW_LOGOS as a back-compat alias for any older references.
const NORDICREW_LOGOS = (typeof BUILT_IN_STICKERS !== 'undefined') ? BUILT_IN_STICKERS : [];

// Initial roster generated from:
// C:\apps\_nordicrew\mmmeerch\Мерч нордисреш.xlsx
// The file has no e-mails, so member-*.nordicrew.local addresses are placeholders
// until the real invite list is imported.
const ROSTER_SOURCE = [
  { id: 'u1', name: 'Эндрю Еж', nickname: 'Эндрю Еж', sourceRows: [5], paid: true, shirts: [
    { color: 'black', size: 'M', fit: 'male', qty: 2 },
    { color: 'white', size: 'L', fit: 'female', qty: 2 },
  ] },
  { id: 'u2', name: 'Артем Романов', nickname: 'Артем Романов', sourceRows: [6], paid: true, shirts: [
    { color: 'black', size: 'M', fit: 'male', qty: 2 },
  ] },
  { id: 'u3', name: 'Виктор Тимофеев', nickname: '@Victor_Timofeev', sourceRows: [7], paid: true, shirts: [
    { color: 'black', size: 'M', fit: 'male', qty: 2 },
  ] },
  { id: 'u4', name: 'MKS', nickname: '@max007258', sourceRows: [8,17], paid: true, designNote: 'Большую С30 на спину, маленький щит на сердце', shirts: [
    { color: 'white', size: 'L', fit: 'male', qty: 1 },
    { color: 'white', size: 'L', fit: 'male', qty: 1 },
  ] },
  { id: 'u5', name: 'Kiruhann', nickname: '@Kiruhann', sourceRows: [9], paid: true, shirts: [
    { color: 'black', size: 'L', fit: 'male', qty: 1 },
  ] },
  { id: 'u6', name: 'Андрей Никитин', nickname: '@nikitin_bokeh', sourceRows: [10], paid: true, shirts: [
    { color: 'white', size: 'L', fit: 'male', qty: 1 },
  ] },
  { id: 'u7', name: 'Alex Bismarck', nickname: 'Alex Bismarck', sourceRows: [11], paid: true, shirts: [
    { color: 'black', size: 'L', fit: 'male', qty: 1 },
  ] },
  { id: 'u8', name: 'Боря Бочаров', nickname: '@bchrv_bors', sourceRows: [12], paid: true, designNote: 'Принты следующие: 1-ый спереди по центру; 2-ой сзади на всю спину', shirts: [
    { color: 'black', size: 'M', fit: 'male', qty: 1 },
  ] },
  { id: 'u9', name: 'Anton Morozov', nickname: '@an_mrz', sourceRows: [13], paid: true, shirts: [
    { color: 'white', size: 'L', fit: 'male', qty: 4 },
  ] },
  { id: 'u10', name: 'Andrey A', nickname: '@metoff', sourceRows: [14], paid: true, shirts: [
    { color: 'black', size: 'M', fit: 'male', qty: 1 },
  ] },
  { id: 'u11', name: 'Сергей', nickname: '@mtrskeen', sourceRows: [15], paid: true, shirts: [
    { color: 'white', size: 'L', fit: 'male', qty: 2 },
    { color: 'black', size: 'L', fit: 'male', qty: 2 },
  ] },
  { id: 'u12', name: 'S. Vladislav', nickname: '@Vladislav_Someone', sourceRows: [16], paid: true, shirts: [
    { color: 'black', size: 'M', fit: 'male', qty: 1 },
  ] },
  { id: 'u13', name: 'Дима', nickname: '@dmitryhtl', sourceRows: [18], paid: false, shirts: [
    { color: 'black', size: 'XL', fit: 'unknown', qty: 1 },
  ] },
];

const SAMPLE_USERS = (() => {
  let shirtCounter = 1;
  return ROSTER_SOURCE.map((u, idx) => {
    const shirtSpecs = u.shirts.flatMap(spec => {
      const qty = Math.max(1, spec.qty || 1);
      return Array.from({ length: qty }, (_, copyIndex) => ({
        ...spec,
        qty: 1,
        batchQty: qty,
        batchCopy: copyIndex + 1,
      }));
    });
    const shirtIds = shirtSpecs.map(() => 's' + shirtCounter++);
    return {
      id: u.id,
      email: `member-${String.fromCharCode(97 + idx)}@nordicrew.local`,
      name: u.name,
      nickname: u.nickname,
      carNumber: String(idx + 1).padStart(2, '0'),
      inviteCode: String(idx + 1).padStart(2, '0').repeat(3).slice(0, 6),
      shirts: shirtIds,
      shirtSpecs,
      paid: u.paid,
      designNote: u.designNote || '',
      sourceRows: u.sourceRows,
      status: 'not-started',
      finishedAt: null,
    };
  });
})();

// Single sleeve zone (one print, one sleeve only)
const ZONES = [
  { id: 'front', label: 'Грудь',  printW: 280, printH: 320, viewLabel: 'Спереди' },
  { id: 'back',  label: 'Спина',  printW: 320, printH: 380, viewLabel: 'Сзади' },
  { id: 'sleeve',label: 'Рукав',  printW: 90,  printH: 110, viewLabel: 'Рукав' },
];

const ZONE_LIMITS = { front: 2, back: 2, sleeve: 1 };

// Pick first few stickers as defaults for sample designs
function pickSticker(idx) {
  const list = (typeof BUILT_IN_STICKERS !== 'undefined') ? BUILT_IN_STICKERS : [];
  if (!list.length) return null;
  return list[idx % list.length].id;
}

// Default design template — admin-editable.
// Stored in % coordinates and uses {{nickname}}/{{number}} placeholders for text items.
// Colors are stored as 'auto' to mean "auto-invert based on shirt color" (white shirt → dark ink, black shirt → light ink).
const DEFAULT_TEMPLATE = {
  front: [
    { id: 'tpl-f1', logoId: 'st-30_circle_outline', x: 50, y: 30, w: 28, h: 28, rotation: 0, color: 'auto' },
  ],
  back: [
    { id: 'tpl-b1', logoId: 'st-12_wordmark_solid_large', x: 50, y: 38, w: 70, h: 30, rotation: 0, color: 'auto' },
    { id: 'tpl-b2', logoId: 'user-text', x: 50, y: 18, w: 50, h: 9, rotation: 0, color: 'auto', customText: '{{nickname}}' },
  ],
  sleeve: [
    { id: 'tpl-s1', logoId: 'st-30_circle_outline', x: 50, y: 50, w: 55, h: 55, rotation: 0, color: 'auto' },
  ],
};

const DEFAULT_TEMPLATES = [
  {
    id: 'tpl-classic',
    name: 'Classic back + chest',
    description: 'Крупный Nordicrew на спине, круглый знак на груди и рукаве.',
    designs: DEFAULT_TEMPLATE,
  },
  {
    id: 'tpl-minimal-front',
    name: 'Minimal front',
    description: 'Акцент на груди, спина остаётся свободной.',
    designs: {
      front: [
        { id: 'tpl-mf1', logoId: 'st-30_circle_outline', x: 50, y: 34, w: 22, h: 22, rotation: 0, color: 'auto' },
      ],
      back: [],
      sleeve: [
        { id: 'tpl-mf2', logoId: 'st-15_wordmark_solid_small', x: 50, y: 50, w: 58, h: 14, rotation: 0, color: 'auto' },
      ],
    },
  },
  {
    id: 'tpl-big-back',
    name: 'Big back',
    description: 'Большой принт на спине и маленький щит на сердце.',
    designs: {
      front: [
        { id: 'tpl-bb1', logoId: 'st-30_circle_outline', x: 33, y: 24, w: 18, h: 18, rotation: 0, color: 'auto' },
      ],
      back: [
        { id: 'tpl-bb2', logoId: 'st-12_wordmark_solid_large', x: 50, y: 38, w: 76, h: 18, rotation: 0, color: 'auto' },
      ],
      sleeve: [],
    },
  },
];

function inkFor(shirtColor) {
  return shirtColor === 'black' ? '#f3f3f1' : '#0a0a0c';
}

// Apply template to a shirt (replaces 'auto' colors with the inverse ink and resolves text placeholders).
function applyTemplate(template, user, shirtColor) {
  const ink = inkFor(shirtColor);
  const out = { front: [], back: [], sleeve: [] };
  for (const zone of ['front', 'back', 'sleeve']) {
    out[zone] = (template[zone] || []).map((item, i) => {
      let txt = item.customText;
      if (typeof txt === 'string') {
        txt = txt.replace(/\{\{nickname\}\}/g, user.nickname || 'NICK')
                 .replace(/\{\{number\}\}/g, user.carNumber || '00')
                 .replace(/\{\{name\}\}/g, user.name || '');
      }
      return {
        ...item,
        id: `${item.id}-${user.id}-${i}`,
        aspectRatio: item.aspectRatio || getLogoAspectRatio(item.logoId, txt, []),
        color: item.color === 'auto' ? ink : item.color,
        customText: txt,
      };
    });
  }
  return out;
}

function generateShirts(template) {
  const shirts = {};
  SAMPLE_USERS.forEach(u => {
    u.shirts.forEach((shirtId, idx) => {
      const spec = u.shirtSpecs?.[idx] || { color: 'black', size: 'L', fit: 'unknown', qty: 1 };
      const color = spec.color;
      const size = spec.size;
      const designs = template ? applyTemplate(template, u, color) : { front: [], back: [], sleeve: [] };
      shirts[shirtId] = {
        id: shirtId,
        userId: u.id,
        color,
        size,
        fit: spec.fit || '',
        batchQty: spec.batchQty || 1,
        batchCopy: spec.batchCopy || 1,
        status: 'empty',
        qty: spec.qty || 1,
        designs,
        updatedAt: null,
      };
    });
  });
  return shirts;
}

// By default — empty shirts. Admin can apply the template later from the admin panel.
const SHIRTS = generateShirts(null);

Object.assign(window, {
  NORDICREW_LOGOS, SAMPLE_USERS, SHIRTS, ZONES, ZONE_LIMITS,
  DEFAULT_TEMPLATE, DEFAULT_TEMPLATES, applyTemplate, inkFor, generateShirts,
});
