import {localized, type Project, type Locale} from './catalog';

export const marketCategories = ['all','tangible','intangible','investment'] as const;
export const marketSorts = ['featured','gainers','losers','price-low','price-high','newest'] as const;
export type MarketSort = typeof marketSorts[number];
export function normalizeSearch(value: string) {
 return value.normalize('NFKC').toLocaleLowerCase().replace(/[يى]/g,'ی').replace(/ك/g,'ک')
  .replace(/[۰-۹]/g,d=>String('۰۱۲۳۴۵۶۷۸۹'.indexOf(d))).replace(/[٠-٩]/g,d=>String('٠١٢٣٤٥٦٧٨٩'.indexOf(d)))
  .replace(/[\u064b-\u065f\u200c\u200d]/g,'').trim();
}
export function marketQuote(project: Project, now = Date.now()) {
 const previous = project.price_24h_ago_rial, current = project.unit_price_rial;
 const date = project.market_updated_at ? Date.parse(project.market_updated_at) : NaN;
 if (!Number.isFinite(previous) || !previous || previous <= 0 || !Number.isSafeInteger(current) || current <= 0 ||
  !Number.isFinite(date) || (!project.is_demo && (now-date > 26*60*60*1000 || date-now > 5*60*1000))) return null;
 const deltaRial = current-previous, percent = deltaRial/previous*100;
 return {percent,deltaRial,direction: deltaRial>0?'up':deltaRial<0?'down':'flat',at:date} as const;
}
export function marketHistory(project: Project, now = Date.now()) {
 const quote=marketQuote(project,now), values=project.price_history_24h;
 if (!quote || !Array.isArray(values) || values.length<2 || values.length>96 || values.some(value=>!Number.isSafeInteger(value)||value<=0) ||
  values[0]!==project.price_24h_ago_rial || values.at(-1)!==project.unit_price_rial) return [];
 return values;
}
export function filterMarket(projects: Project[], query: string, category: string, sort: MarketSort, locale: Locale, now = Date.now()) {
 const terms=normalizeSearch(query).split(/\s+/).filter(Boolean);
 const results=projects.filter(project=>{
  if(category!=='all'&&project.category!==category)return false;
  const searchable=normalizeSearch([project.symbol,project.slug,localized(project.title,locale),...Object.values(project.title),...Object.values(project.subtitle),...Object.values(project.location)].join(' '));
  return terms.every(term=>searchable.includes(term));
 });
 return results.sort((a,b)=>{
  if(sort==='price-low')return a.unit_price_rial-b.unit_price_rial;
  if(sort==='price-high')return b.unit_price_rial-a.unit_price_rial;
  if(sort==='newest')return (Date.parse(b.created_at||b.updated_at)||0)-(Date.parse(a.created_at||a.updated_at)||0)||a.sort_order-b.sort_order;
  if(sort==='gainers'||sort==='losers'){
   const x=marketQuote(a,now),y=marketQuote(b,now);
   if(!x||!y)return x?-1:y?1:a.sort_order-b.sort_order;
   return (sort==='gainers'?-1:1)*(x.percent-y.percent)||a.sort_order-b.sort_order;
  }
  return a.sort_order-b.sort_order;
 });
}
export const projectHref=(project:Project,preview=false)=>`/projects/${project.slug}${preview?'?preview=design':''}`;
