// WTS Cyprus — TP module mock data (Build Track MVP model)
// AI enrichment generates ONLY the Detailed Business Description + evidence +
// rule-based criteria flags. Accept / Reject is a MANUAL analyst verdict.
// (AI-suggested verdict pre-fill is deferred to Phase 2 — not modelled here.)

// ── Deterministic PRNG (mulberry32) ──────────────────────────────────────
const _mkRng = (seed) => {
  let t = seed >>> 0;
  return () => {
    t |= 0; t = t + 0x6D2B79F5 | 0;
    let r = Math.imul(t ^ t >>> 15, 1 | t);
    r = r + Math.imul(r ^ r >>> 7, 61 | r) ^ r;
    return ((r ^ r >>> 14) >>> 0) / 4294967296;
  };
};
const _pick = (rng, arr) => arr[Math.floor(rng() * arr.length)];

const _COUNTRIES = [
  { code: 'DE', flag: '🇩🇪', surnames: ['Müller','Schmidt','Bauer','Wagner','Fischer','Weber','Hoffmann','Becker','Schulz','Kraus','Lehmann','Vogel'],         types: ['Handels GmbH','Vertrieb GmbH','Distribution GmbH','Logistik GmbH','Trading GmbH','Pharma GmbH','Industrie GmbH'] },
  { code: 'FR', flag: '🇫🇷', surnames: ['Lavoisier','Bernard','Dupont','Moreau','Lefèvre','Roux','Petit','Mercier','Allard','Caron','Bonnet','Faure'],         types: ['Distribution SAS','Industrie SA','Trading SAS','Logistique SA','Diffusion SAS'] },
  { code: 'IT', flag: '🇮🇹', surnames: ['Rossi','Bianchi','Ferrari','Esposito','Romano','Conti','Greco','Marino','Costa','Bruno','Galli','Riva'],              types: ['Distribuzione SpA','Industriale SpA','Logistica Srl','Commerciale Srl','Servizi SpA'] },
  { code: 'NL', flag: '🇳🇱', surnames: ['de Vries','Jansen','van Dijk','Bakker','Visser','Smit','Mulder','Bos','Vermeer','Hendriks','Peters','Brouwer'],      types: ['Logistics BV','Distribution BV','Trading BV','Holding BV','Industries NV'] },
  { code: 'ES', flag: '🇪🇸', surnames: ['García','Fernández','Rodríguez','López','Martínez','Sánchez','Pérez','Gómez','Ruiz','Hernández','Díaz','Álvarez'], types: ['Distribución SL','Comercial SA','Logística SL','Industrias SA','Servicios SL'] },
  { code: 'SE', flag: '🇸🇪', surnames: ['Andersson','Johansson','Karlsson','Nilsson','Eriksson','Larsson','Olsson','Persson','Lindgren','Berg','Lundberg'],   types: ['Trading AB','Distribution AB','Logistik AB','Industri AB','Handel AB'] },
  { code: 'FI', flag: '🇫🇮', surnames: ['Korhonen','Virtanen','Mäkinen','Nieminen','Hämäläinen','Laine','Heikkinen','Koskinen'],                              types: ['Trading OY','Logistiikka OY','Pharma OY','Industrial OY'] },
  { code: 'GB', flag: '🇬🇧', surnames: ['Albion','Thames','Northbridge','Westfield','Crownmark','Sterling','Kingsway','Pendragon','Mercia','Holborn'],         types: ['Distribution Ltd','Trading Ltd','Logistics Ltd','Industries Ltd','Holdings PLC'] },
  { code: 'AT', flag: '🇦🇹', surnames: ['Gruber','Steiner','Wagner','Maier','Berger','Lechner','Wolf'],                                                       types: ['Handels GmbH','Vertriebs GmbH','Industrie GmbH'] },
  { code: 'BE', flag: '🇧🇪', surnames: ['Janssens','Maes','Peeters','Mertens','Claes','Wouters','Dubois','Lambert'],                                          types: ['Distribution BV','Logistics SA','Trading NV','Commerce SA'] },
];

const _STUDY_PROFILES = {
  s1: { seed: 17, count: 187, reviewedCount: 187,
    nace: { code: '46.46', label: 'Wholesale of pharmaceutical goods' }, turnoverMin: 5_000_000, turnoverMax: 50_000_000,
    descTemplates: [
      n => `${n.name} is a ${n.cityAdj}-based independent wholesaler of pharmaceutical and parapharmaceutical products serving retail pharmacies and hospital networks. The company operates a single distribution centre and does not engage in manufacturing, marketing authorisation, or research activities.`,
      n => `${n.name} is an independent distributor of prescription and over-the-counter pharmaceutical products to community pharmacies across ${n.country}. The business is purely commercial — sourcing from licensed manufacturers and supplying licensed retailers — with no clinical or R&D operations.`,
      n => `${n.name} operates as a regional wholesaler of pharmaceutical goods including generic medicines, medical devices and parapharmacy lines. Annual revenue derives almost entirely from sales to third-party pharmacies and hospitals in ${n.country}.`,
    ],
    rejectDescTemplates: [
      n => `${n.name} is a wholly-owned subsidiary of ${n.parent} active in pharmaceutical distribution across ${n.country}. Intercompany supply arrangements with the parent group represent the majority of cost of goods sold.`,
      n => `${n.name} combines pharmaceutical wholesaling with own-brand manufacturing of generic medicines at a facility in ${n.country}. Manufacturing revenue accounted for approximately 35% of FY2024 turnover.`,
      n => `${n.name} engages in the wholesale and retail distribution of cosmetics and parapharmacy products. Prescription pharmaceuticals represent a minor share of revenue (under 20%).`,
    ] },
  s2: { seed: 23, count: 142, reviewedCount: 92,
    nace: { code: '74.90', label: 'Other professional, scientific and technical activities' }, turnoverMin: 2_000_000, turnoverMax: 25_000_000,
    descTemplates: [
      n => `${n.name} is an independent licensor of industrial and process know-how to manufacturers in ${n.country} and adjacent EU markets. The company derives its revenue from running royalties on licensed technology portfolios developed in-house since the 1990s.`,
      n => `${n.name} operates as a pure-play IP holding and licensing entity. Its sole activity is granting non-exclusive licences on a portfolio of trademarks and know-how to third-party operators on running-royalty terms.`,
      n => `${n.name} owns and licenses a portfolio of brand IP and patented technology in the consumer products space. All licensing arrangements are with unrelated third parties on arm's-length terms.`,
    ],
    rejectDescTemplates: [
      n => `${n.name} is the IP holding entity of the ${n.parent} group, licensing trademarks and patents exclusively to affiliated operating companies. Royalty revenue is intercompany in nature.`,
      n => `${n.name} is a distributor of branded consumer goods under licence from third-party brand owners; it is itself a licensee, not a licensor.`,
      n => `${n.name} provides marketing consultancy and brand management services on a fee basis. The company does not own a meaningful IP portfolio of its own.`,
    ] },
  s3: { seed: 31, count: 234, reviewedCount: 0,
    nace: { code: '68.32', label: 'Management of real estate on a fee or contract basis' }, turnoverMin: 1_000_000, turnoverMax: 20_000_000,
    descTemplates: [
      n => `${n.name} provides commercial real estate management services to third-party landlords on a fee or contract basis. The business covers leasing administration, tenant relations, and facilities management for office and retail properties in ${n.country}.`,
      n => `${n.name} is an independent property management firm serving institutional landlords and family offices in ${n.country}. Revenue is generated entirely from management fees on a portfolio of commercial assets owned by unrelated parties.`,
      n => `${n.name} manages residential and commercial property portfolios on behalf of third-party owners under multi-year service agreements. The company does not own real estate on its own balance sheet beyond office premises.`,
    ],
    rejectDescTemplates: [
      n => `${n.name} owns and operates a portfolio of commercial real estate assets in ${n.country}. Rental income from owned properties represents the substantial majority of turnover.`,
      n => `${n.name} is the property management subsidiary of the ${n.parent} group, managing real estate exclusively for affiliated operating companies.`,
      n => `${n.name} operates as a real estate broker on a brokerage-commission basis. The activity profile differs from a management-fee model.`,
    ] },
};

const _CITY_ADJ = {
  DE: ['Munich','Hamburg','Frankfurt','Stuttgart','Cologne','Berlin','Düsseldorf'], FR: ['Paris','Lyon','Toulouse','Bordeaux','Nantes','Marseille','Lille'],
  IT: ['Milan','Rome','Turin','Bologna','Florence','Verona'], NL: ['Amsterdam','Rotterdam','Utrecht','Eindhoven','The Hague'],
  ES: ['Madrid','Barcelona','Valencia','Bilbao','Seville'], SE: ['Stockholm','Gothenburg','Malmö','Uppsala'], FI: ['Helsinki','Espoo','Tampere'],
  GB: ['London','Manchester','Birmingham','Leeds','Bristol'], CY: ['Nicosia','Limassol','Larnaca'], AT: ['Vienna','Graz','Linz','Salzburg'], BE: ['Brussels','Antwerp','Ghent','Liège'],
};
const _PARENT_NAMES = ['Sanofi Distribution Europe SA','Bayer Health Group AG','GlaxoUnion PLC','PharmaNova Holdings SE','EuroLogistik Holding GmbH','MedSupply Group BV','BrandWorks Holding SE','Continental Property Group BV','Mediterraneo Holding SpA','Adriatic Estates Group SpA'];
const _formatCountry = (code) => ({DE:'Germany',FR:'France',IT:'Italy',NL:'the Netherlands',ES:'Spain',SE:'Sweden',FI:'Finland',GB:'the United Kingdom',CY:'Cyprus',AT:'Austria',BE:'Belgium'}[code] || code);

// ── Candidate + enrichment generator ─────────────────────────────────────
const _genStudy = (studyId, profile) => {
  const rng = _mkRng(profile.seed);
  const cands = [], enrichments = [], verdicts = [];
  for (let i = 0; i < profile.count; i++) {
    const country = _pick(rng, _COUNTRIES);
    const companyName = `${_pick(rng, country.surnames)} ${_pick(rng, country.types)}`;
    const cityAdj = _pick(rng, _CITY_ADJ[country.code] || ['regional']);

    // Objective attributes
    const independent = rng() < 0.80;
    const turnoverIn  = rng() < 0.85;
    const activityOk  = rng() < 0.82;
    const geoOk       = rng() < 0.96;
    const lossMaking  = rng() < 0.10;
    const allPass     = independent && turnoverIn && activityOk && geoOk && !lossMaking;

    let turnover;
    if (!turnoverIn) {
      turnover = rng() < 0.5 ? Math.round(profile.turnoverMin * (0.15 + rng() * 0.5)) : Math.round(profile.turnoverMax * (1.4 + rng() * 1.2));
    } else {
      turnover = Math.round(profile.turnoverMin + rng() * (profile.turnoverMax - profile.turnoverMin));
    }
    const employees = 20 + Math.floor(rng() * 300);
    const parent = !independent ? _pick(rng, _PARENT_NAMES) : null;
    const tplPool = allPass ? profile.descTemplates : profile.rejectDescTemplates;
    const tpl = tplPool[Math.floor(rng() * tplPool.length)];
    const businessDescription = tpl({ name: companyName, country: _formatCountry(country.code), parent, cityAdj });

    const id = `cand-${studyId}-${String(i + 1).padStart(3, '0')}`;
    cands.push({
      id, studyId, companyName,
      country: country.code, countryFlag: country.flag, countryLabel: _formatCountry(country.code),
      naceCode: profile.nace.code, naceLabel: profile.nace.label,
      turnover, employees, independent, lossMaking2024: lossMaking, businessDescription,
    });

    const flags = {
      independence: { pass: independent, evidence: independent ? 'No group ownership disclosed in the ownership section.' : `"wholly-owned subsidiary of ${parent}"` },
      activity:     { pass: activityOk,  evidence: '"' + businessDescription.split('. ')[0].slice(0, 110) + '"' },
      geography:    { pass: geoOk,       evidence: `${_formatCountry(country.code)} (${geoOk ? 'within' : 'outside'} declared market scope).` },
      size:         { pass: turnoverIn,  evidence: turnoverIn ? `Turnover €${(turnover/1e6).toFixed(1)}M within band €${profile.turnoverMin/1e6}M–€${profile.turnoverMax/1e6}M.` : `Turnover €${(turnover/1e6).toFixed(1)}M outside band.` },
    };
    enrichments.push({
      id: `enr-${id}`, candidateId: id, studyId, status: 'done',
      primaryEvidenceQuote: !independent && parent ? `"wholly-owned subsidiary of ${parent}"` : businessDescription.split('. ')[0],
      criteriaFlags: flags, modelVersion: 'claude-sonnet-4', promptVersion: 'v1.3',
      enrichedAt: '2025-05-15T14:32:00Z', fetchUrl: `https://www.${companyName.toLowerCase().replace(/[^a-z]+/g, '')}.com`,
    });

    // Seed an analyst verdict for the first reviewedCount candidates
    if (i < profile.reviewedCount) {
      const verdict = allPass ? 'accept' : 'reject';
      let reason;
      if (verdict === 'accept') {
        reason = `Independent ${profile.nace.label.toLowerCase()} provider; turnover, geography and functional profile all align with the tested party.`;
      } else {
        const fails = [];
        if (!independent) fails.push('independence (group-affiliated)');
        if (!activityOk)  fails.push('functional-profile match');
        if (!turnoverIn)  fails.push('turnover band');
        if (!geoOk)       fails.push('geographic scope');
        if (lossMaking)   fails.push('loss-making in the tested period');
        reason = `Fails ${fails.join(' and ')}. Not retained as a comparable.`;
      }
      verdicts.push({
        id: `vrd-${id}`, candidateId: id, studyId, verdict, reason,
        userId: studyId === 's1' ? 'u3' : 'u5', createdAt: '2025-05-15T15:10:00Z',
        history: [{ verdict, reason, userId: studyId === 's1' ? 'u3' : 'u5', at: '2025-05-15T15:10:00Z' }],
      });
    }
  }
  return { cands, enrichments, verdicts };
};

const CANDIDATES = [], ENRICHMENTS = [], VERDICTS = [];
for (const sid of Object.keys(_STUDY_PROFILES)) {
  const { cands, enrichments, verdicts } = _genStudy(sid, _STUDY_PROFILES[sid]);
  CANDIDATES.push(...cands); ENRICHMENTS.push(...enrichments); VERDICTS.push(...verdicts);
}

// s4 (Software Services Benchmark) — draft: candidates uploaded, not yet enriched
{
  const rng = _mkRng(41);
  for (let i = 0; i < 96; i++) {
    const country = _pick(rng, _COUNTRIES);
    const id = `cand-s4-${String(i + 1).padStart(3, '0')}`;
    CANDIDATES.push({
      id, studyId: 's4',
      companyName: `${_pick(rng, country.surnames)} Software ${_pick(rng, country.types).replace(/Handels |Vertrieb |Distribution |Trading |Logistics |Logistik |Distribuzione |Diffusion /,'')}`,
      country: country.code, countryFlag: country.flag, countryLabel: _formatCountry(country.code),
      naceCode: '62.01', naceLabel: 'Computer programming activities',
      turnover: Math.round(1_500_000 + rng() * 15_000_000), employees: 15 + Math.floor(rng() * 220),
      independent: rng() < 0.7, lossMaking2024: rng() < 0.15,
      businessDescription: `Independent provider of bespoke software development and IT consulting services to enterprise clients across ${_formatCountry(country.code)}.`,
    });
  }
}

// ── Helpers exposed for UI ──────────────────────────────────────────────
const getCandidatesForStudy   = (sid) => CANDIDATES.filter(c => c.studyId === sid);
const getEnrichmentForCandidate = (cid) => ENRICHMENTS.find(e => e.candidateId === cid);
const getVerdictForCandidate  = (cid) => VERDICTS.find(v => v.candidateId === cid);
const formatEUR = (n) => {
  if (n == null) return '—';
  if (n >= 1e6) return '€ ' + (n / 1e6).toFixed(1) + 'M';
  if (n >= 1e3) return '€ ' + (n / 1e3).toFixed(0) + 'k';
  return '€ ' + n;
};
const studyVerdictBreakdown = (sid) => {
  const cands = getCandidatesForStudy(sid);
  const v = VERDICTS.filter(x => x.studyId === sid);
  return {
    accept:  v.filter(x => x.verdict === 'accept').length,
    reject:  v.filter(x => x.verdict === 'reject').length,
    pending: cands.length - v.length,
  };
};

Object.assign(window, {
  CANDIDATES, ENRICHMENTS, VERDICTS,
  getCandidatesForStudy, getEnrichmentForCandidate, getVerdictForCandidate,
  formatEUR, studyVerdictBreakdown,
});
