
// ════════════════════════════════════════════════════════════════════
//  InvestorQuiz — a 10-question dynamic assessment that grades the
//  visitor into an investor archetype, then shows: (left) the archetype
//  + explanation, (right) a real example project with the returns that
//  similar investors realized, and (below) what investors like them
//  hold beyond real estate.
// ════════════════════════════════════════════════════════════════════

const QZ_INK   = '#2C2C2A';
const QZ_CREAM = '#F4F1EC';
const QZ_GOLD  = '#B8922A';
const QZ_GOLDL = '#D4AF6A';
const QZ_MUTE  = '#8A8A85';

// ─── Minimal geometric glyphs (abstract marks, on-brand line work) ───
const Glyph = ({ name, size = 30, color = QZ_INK, opacity = 0.6 }) => {
  const c = { stroke: color, strokeWidth: 1, fill: 'none', strokeLinecap: 'round', strokeLinejoin: 'round' };
  const paths = {
    rise:    [['polyline', { points: '6,26 16,16 22,21 34,8' }], ['polyline', { points: '27,8 34,8 34,15' }]],
    shield:  [['path', { d: 'M20 5 L33 10 V20 C33 28 27 33 20 36 C13 33 7 28 7 20 V10 Z' }]],
    sun:     [['circle', { cx: 20, cy: 20, r: 7 }], ['line', { x1: 20, y1: 4, x2: 20, y2: 9 }], ['line', { x1: 20, y1: 31, x2: 20, y2: 36 }], ['line', { x1: 4, y1: 20, x2: 9, y2: 20 }], ['line', { x1: 31, y1: 20, x2: 36, y2: 20 }]],
    globe:   [['circle', { cx: 20, cy: 20, r: 14 }], ['ellipse', { cx: 20, cy: 20, rx: 6, ry: 14 }], ['line', { x1: 6, y1: 20, x2: 34, y2: 20 }]],
    spark:   [['line', { x1: 20, y1: 5, x2: 20, y2: 35 }], ['line', { x1: 5, y1: 20, x2: 35, y2: 20 }], ['line', { x1: 9, y1: 9, x2: 31, y2: 31 }], ['line', { x1: 31, y1: 9, x2: 9, y2: 31 }]],
    clock:   [['circle', { cx: 20, cy: 20, r: 14 }], ['polyline', { points: '20,11 20,20 27,24' }]],
    leaf:    [['path', { d: 'M9 31 C9 14 24 9 32 9 C32 26 18 31 9 31 Z' }], ['line', { x1: 9, y1: 31, x2: 22, y2: 18 }]],
    scales:  [['line', { x1: 20, y1: 7, x2: 20, y2: 31 }], ['line', { x1: 9, y1: 13, x2: 31, y2: 13 }], ['path', { d: 'M9 13 L5 23 H13 Z' }], ['path', { d: 'M31 13 L27 23 H35 Z' }]],
    hour:    [['path', { d: 'M9 6 H31 L21 20 L31 34 H9 L19 20 Z' }]],
    home:    [['polyline', { points: '7,19 20,7 33,19' }], ['polyline', { points: '11,17 11,33 29,33 29,17' }]],
    wave:    [['path', { d: 'M5 24 C10 16 14 16 20 22 C26 28 30 28 35 20' }], ['path', { d: 'M5 31 C10 23 14 23 20 29 C26 35 30 35 35 27' }]],
    coins:   [['ellipse', { cx: 20, cy: 13, rx: 12, ry: 4.5 }], ['path', { d: 'M8 13 V21 C8 23.5 13.4 25.5 20 25.5 C26.6 25.5 32 23.5 32 21 V13' }], ['path', { d: 'M8 21 V27 C8 29.5 13.4 31.5 20 31.5 C26.6 31.5 32 29.5 32 27 V21' }]],
    layers:  [['polygon', { points: '20,6 35,14 20,22 5,14' }], ['polyline', { points: '5,21 20,29 35,21' }], ['polyline', { points: '5,28 20,36 35,28' }]],
    compass: [['circle', { cx: 20, cy: 20, r: 14 }], ['polygon', { points: '20,11 24,20 20,29 16,20' }]],
    target:  [['circle', { cx: 20, cy: 20, r: 14 }], ['circle', { cx: 20, cy: 20, r: 7 }], ['circle', { cx: 20, cy: 20, r: 1.4, fill: color, stroke: 'none' }]],
    key:     [['circle', { cx: 13, cy: 20, r: 7 }], ['line', { x1: 20, y1: 20, x2: 35, y2: 20 }], ['line', { x1: 30, y1: 20, x2: 30, y2: 26 }], ['line', { x1: 35, y1: 20, x2: 35, y2: 27 }]],
    grid:    [['line', { x1: 15, y1: 6, x2: 15, y2: 34 }], ['line', { x1: 25, y1: 6, x2: 25, y2: 34 }], ['line', { x1: 6, y1: 15, x2: 34, y2: 15 }], ['line', { x1: 6, y1: 25, x2: 34, y2: 25 }]],
    map:     [['polygon', { points: '7,9 16,13 24,9 33,13 33,31 24,27 16,31 7,27' }], ['line', { x1: 16, y1: 13, x2: 16, y2: 31 }], ['line', { x1: 24, y1: 9, x2: 24, y2: 27 }]],
    door:    [['rect', { x: 11, y: 7, width: 18, height: 27 }], ['circle', { cx: 24, cy: 21, r: 1.4, fill: color, stroke: 'none' }]],
    flag:    [['line', { x1: 11, y1: 6, x2: 11, y2: 34 }], ['path', { d: 'M11 8 H31 L26 14 L31 20 H11 Z' }]],
  };
  const items = paths[name] || paths.target;
  return React.createElement('svg', { viewBox: '0 0 40 40', width: size, height: size, style: { display: 'block', opacity } },
    items.map(([tag, attrs], i) => React.createElement(tag, { key: i, ...c, ...attrs }))
  );
};

// ─── Questions ───────────────────────────────────────────────────────
// Each option carries a score across three axes: growth / safety / lifestyle.
const QUIZ_QUESTIONS = [
  {
    eyebrow: 'Motivation',
    q: 'What is the real reason you want to own property abroad?',
    help: 'There is no wrong answer — it simply shapes everything that follows.',
    type: 'single',
    options: [
      { id: 'q1a', icon: 'rise',   t: 'Build wealth faster than anything at home', s: { growth: 3 } },
      { id: 'q1b', icon: 'shield', t: 'Protect what I have built from inflation',  s: { safety: 3 } },
      { id: 'q1c', icon: 'sun',    t: 'Create a base in a warmer part of the world', s: { lifestyle: 3 } },
      { id: 'q1d', icon: 'globe',  t: 'Diversify out of a single economy',          s: { growth: 1, safety: 2 } },
    ],
  },
  {
    eyebrow: 'Temperament',
    q: 'How would you describe your relationship with risk?',
    help: null,
    type: 'single',
    options: [
      { id: 'q2a', icon: 'spark',  t: "I'll take volatility for a bigger outcome",   s: { growth: 3 } },
      { id: 'q2b', icon: 'clock',  t: 'I want measured, predictable growth',          s: { safety: 3 } },
      { id: 'q2c', icon: 'leaf',   t: 'Comfort and place matter more than max return', s: { lifestyle: 3 } },
      { id: 'q2d', icon: 'scales', t: 'Balanced — a little of each',                  s: { growth: 1, safety: 1, lifestyle: 1 } },
    ],
  },
  {
    eyebrow: 'Time horizon',
    q: 'When do you imagine getting your capital back out?',
    help: null,
    type: 'single',
    options: [
      { id: 'q3a', icon: 'hour',  t: 'Under 4 years — in and out',          s: { growth: 3 } },
      { id: 'q3b', icon: 'clock', t: 'Five to eight years',                 s: { growth: 1, safety: 2 } },
      { id: 'q3c', icon: 'home',  t: 'Eight years or more — generational',  s: { safety: 1, lifestyle: 2 } },
      { id: 'q3d', icon: 'wave',  t: 'No fixed exit — it depends on life',  s: { lifestyle: 3 } },
    ],
  },
  {
    eyebrow: 'Capital',
    q: 'How much are you looking to put to work?',
    help: 'A range is perfectly fine.',
    type: 'single',
    options: [
      { id: 'q4a', icon: 'coins',  t: 'Under €200,000',     s: { safety: 2, lifestyle: 1 } },
      { id: 'q4b', icon: 'coins',  t: '€200,000 – €500,000', s: { growth: 1, safety: 1 } },
      { id: 'q4c', icon: 'layers', t: '€500,000 – €1M',      s: { growth: 2 } },
      { id: 'q4d', icon: 'layers', t: 'Over €1M',            s: { growth: 3 } },
    ],
  },
  {
    eyebrow: 'Context',
    q: 'Where does this sit in your wider picture?',
    help: null,
    type: 'single',
    options: [
      { id: 'q5a', icon: 'door',   t: 'My first property investment',           s: { safety: 2, lifestyle: 1 } },
      { id: 'q5b', icon: 'grid',   t: 'Adding to a property portfolio',         s: { growth: 2 } },
      { id: 'q5c', icon: 'scales', t: 'Diversifying a financial portfolio',     s: { growth: 1, safety: 2 } },
      { id: 'q5d', icon: 'sun',    t: 'A lifestyle decision first, investment second', s: { lifestyle: 3 } },
    ],
  },
  {
    eyebrow: 'Priorities',
    q: 'Which of these matters most to you?',
    help: 'Pick the one that matters most.',
    type: 'single',
    layout: 'grid',
    options: [
      { id: 'q6a', icon: 'rise',   t: 'Capital appreciation',  s: { growth: 2 } },
      { id: 'q6b', icon: 'coins',  t: 'Rental income',         s: { safety: 2 } },
      { id: 'q6c', icon: 'globe',  t: 'USD / currency hedge',  s: { safety: 2 } },
      { id: 'q6d', icon: 'sun',    t: 'Personal use',          s: { lifestyle: 3 } },
      { id: 'q6e', icon: 'home',   t: 'Legacy for family',     s: { safety: 1, lifestyle: 1 } },
      { id: 'q6f', icon: 'key',    t: 'Early off-market access', s: { growth: 2 } },
    ],
  },
  {
    eyebrow: 'Involvement',
    q: 'How hands-on do you want to be?',
    help: null,
    type: 'single',
    options: [
      { id: 'q7a', icon: 'leaf',   t: 'Fully hands-off — manage it for me',  s: { safety: 1, lifestyle: 1 } },
      { id: 'q7b', icon: 'target', t: 'I want to understand every number',   s: { growth: 2 } },
      { id: 'q7c', icon: 'compass',t: 'Involved at the key moments',         s: { growth: 1, safety: 1 } },
      { id: 'q7d', icon: 'door',   t: 'I want to use it myself',             s: { lifestyle: 3 } },
    ],
  },
  {
    eyebrow: 'Entry point',
    q: 'How do you feel about buying before it is built?',
    help: 'Pre-construction and off-market entry carry the deepest pricing.',
    type: 'single',
    options: [
      { id: 'q8a', icon: 'spark',  t: 'Love it — earliest means best price',  s: { growth: 3 } },
      { id: 'q8b', icon: 'scales', t: 'Open to it if the developer is proven', s: { growth: 1, safety: 1 } },
      { id: 'q8c', icon: 'shield', t: 'Prefer something already standing',     s: { safety: 2, lifestyle: 1 } },
      { id: 'q8d', icon: 'sun',    t: 'Prefer ready to enjoy from day one',    s: { lifestyle: 2, safety: 1 } },
    ],
  },
  {
    eyebrow: 'Deal-breakers',
    q: 'What would make you walk away from a deal?',
    help: null,
    type: 'single',
    options: [
      { id: 'q9a', icon: 'hour',   t: 'An unclear exit or poor liquidity', s: { growth: 2 } },
      { id: 'q9b', icon: 'shield', t: 'Construction or delivery risk',     s: { safety: 3 } },
      { id: 'q9c', icon: 'map',    t: 'The wrong location or feel',        s: { lifestyle: 2 } },
      { id: 'q9d', icon: 'coins',  t: 'A thin margin or overpriced entry', s: { growth: 2 } },
    ],
  },
  {
    eyebrow: 'Success',
    q: 'When you imagine the exit, what does success look like?',
    help: null,
    type: 'single',
    options: [
      { id: 'q10a', icon: 'rise',   t: "A number on a spreadsheet I'm proud of", s: { growth: 3 } },
      { id: 'q10b', icon: 'shield', t: 'Capital intact and quietly grown',       s: { safety: 3 } },
      { id: 'q10c', icon: 'sun',    t: 'Years of use, then a clean sale',        s: { lifestyle: 3 } },
      { id: 'q10d', icon: 'layers', t: 'A portfolio that compounds',             s: { growth: 1, safety: 2 } },
    ],
  },
];

// ─── Archetypes (the grading outcomes) ───────────────────────────────
const QUIZ_ARCHETYPES = {
  growth: {
    key: 'growth', profileId: 'growth', flag: 'Accelerator', fin: 'preconstruction',
    name: 'The Accelerator',
    sub: 'You make capital work harder than it ever could at home.',
    desc: 'You are here for the upside. You accept volatility and shorter holds in exchange for the earliest possible entry — pre-construction, off-market, before the market has priced the opportunity. Your edge is timing and access, and you want every number in front of you.',
    traits: [['Risk appetite', 'High'], ['Horizon', '3–5 years'], ['Edge', 'Earliest access']],
    sketch: 'FinancialTower',
    project: {
      name: 'Nayamara', developer: 'TheVelopers', loc: 'Panama City',
      approach: 'Off-market, pre-construction entry',
      why: 'Accelerators entered Nayamara on Lista Cero — before public launch — and exited into a finished, fully-priced building. The deepest discount, the longest runway, the biggest swing.',
      roi: '+118%', roiLabel: 'Realized ROI on committed capital', annual: '+21.4% annualised',
      rows: [['Median entry', '€420,000'], ['Hold period', '4.2 yrs'], ['Discount captured', '6.0%'], ['Gross appreciation', '+31%'], ['Exit & transfer costs', '−4%']],
      sample: 'Based on 14 Dproperty investors with a similar profile in this project.',
    },
    beyond: {
      note: 'Accelerators rarely stop at property. Their wider capital tilts hard toward growth, held through the swings.',
      items: [['Global & growth equities', 45], ['Private & venture', 18], ['Crypto & alternatives', 12], ['Bonds', 10], ['Cash buffer', 15]],
    },
  },
  safety: {
    key: 'safety', profileId: 'safety', flag: 'Preserver', fin: 'finished',
    name: 'The Preserver',
    sub: 'You want what you have built to grow quietly and stay intact.',
    desc: 'You are protecting capital against European inflation and a single-economy risk. You favour established districts, proven developers and dependable rental demand over the biggest possible swing. Measured, USD-denominated, predictable — that is the win.',
    traits: [['Risk appetite', 'Measured'], ['Horizon', '5–8 years'], ['Edge', 'Stability & yield']],
    sketch: 'StandardTower',
    project: {
      name: 'Bioma', developer: 'TheVelopers', loc: 'Panama City',
      approach: 'Pre-sale in an established district',
      why: 'Preservers entered Bioma at pre-sale pricing in a proven district, then held through delivery. Steady appreciation plus reliable rental income — capital that grew without keeping anyone up at night.',
      roi: '+52%', roiLabel: 'Realized ROI on committed capital', annual: '+8.9% annualised',
      rows: [['Median entry', '€310,000'], ['Hold period', '6.0 yrs'], ['Net rental yield', '5.2% / yr'], ['Gross appreciation', '+24%'], ['Exit & transfer costs', '−4%']],
      sample: 'Based on 22 Dproperty investors with a similar profile in this project.',
    },
    beyond: {
      note: 'Preservers build a wider portfolio around income and resilience, not headlines.',
      items: [['Government & corporate bonds', 38], ['Dividend equities', 24], ['High-yield savings & money market', 26], ['Index funds', 12]],
    },
  },
  lifestyle: {
    key: 'lifestyle', profileId: 'lifestyle', flag: 'Lifestyle Strategist', fin: 'finished',
    name: 'The Lifestyle Strategist',
    sub: 'You structure the return so the life becomes possible.',
    desc: 'The spreadsheet is not the only point. You want beachfront access, a warm base, a foothold in another world — structured so the financial return underwrites the personal one. You buy something you will actually use, and let it pay for itself.',
    traits: [['Risk appetite', 'Patient'], ['Horizon', 'Long-term'], ['Edge', 'Use + return']],
    sketch: 'CoastalTower',
    project: {
      name: 'Playa Escondida', developer: 'Playa Escondida', loc: 'Pacific Coast',
      approach: 'Beachfront, held for use and yield',
      why: 'Lifestyle Strategists used Playa Escondida several weeks a year and let managed rental cover the carry. A long, patient hold turned a personal base into a quietly appreciating asset.',
      roi: '+44%', roiLabel: 'Realized ROI on committed capital', annual: '+7.1% annualised',
      rows: [['Median entry', '€265,000'], ['Hold period', '7.0 yrs'], ['Personal use', '≈ 8 weeks / yr'], ['Rental offset', '~60% of carry'], ['Gross appreciation', '+22%']],
      sample: 'Based on 9 Dproperty investors with a similar profile in this project.',
    },
    beyond: {
      note: 'Lifestyle Strategists keep their wider money simple, so attention stays on living well.',
      items: [['Index funds & ETFs', 40], ['Bonds', 18], ['Savings & cash', 22], ['Collectibles & lifestyle assets', 20]],
    },
  },
  balanced: {
    key: 'balanced', profileId: 'growth', flag: 'Balanced Builder', fin: 'construction',
    name: 'The Balanced Builder',
    sub: 'You want the upside, but never at the cost of sleep.',
    desc: 'You sit deliberately between growth and preservation. You will reach for an off-market entry, but you want a proven developer and a clear exit underneath it. You compound steadily across a few well-chosen positions rather than betting on one.',
    traits: [['Risk appetite', 'Balanced'], ['Horizon', '4–7 years'], ['Edge', 'Diversified entries']],
    sketch: 'LowRiseBuilding',
    project: {
      name: 'Mova', developer: 'Pacific Developers', loc: 'Punta Cana',
      approach: 'Under-construction entry, proven developer',
      why: 'Balanced Builders entered Mova once construction was underway — a faster, safer position than raw pre-sale, while still capturing developer pricing and strong Punta Cana rental demand.',
      roi: '+71%', roiLabel: 'Realized ROI on committed capital', annual: '+12.8% annualised',
      rows: [['Median entry', '€285,000'], ['Hold period', '4.5 yrs'], ['Net rental yield', '6.1% / yr'], ['Gross appreciation', '+27%'], ['Exit & transfer costs', '−4%']],
      sample: 'Based on 17 Dproperty investors with a similar profile in this project.',
    },
    beyond: {
      note: 'Balanced Builders mirror their property approach in everything else: growth, with ballast.',
      items: [['Index funds & ETFs', 40], ['Bonds', 25], ['Savings & cash', 20], ['Growth equities', 15]],
    },
  },
};

// ─── Minimum-investment structures (keyed by archetype.fin) ──────────
const QUIZ_FINANCING = {
  preconstruction: {
    stage: 'Pre-construction · off-market',
    headline: 'The earliest entry — the lowest in, the most flexible terms.',
    type: 'plan',
    down: '€15,000', downLabel: 'Minimum down payment',
    then: '€75,000', thenLabel: 'Remaining capital',
    schedule: 'Paid on a schedule we arrange with you — usually monthly across 36 months, but negotiable to fit you.',
  },
  construction: {
    stage: 'Already under construction',
    headline: 'Buy into a project already on its way — the Gesti route.',
    type: 'plan',
    down: '€15,000', downLabel: 'Down payment',
    then: '€1,500/mo', thenLabel: 'Monthly payment',
    schedule: 'Twenty-four monthly payments of €1,500 — €36,000 in total — carrying you through to delivery.',
  },
  finished: {
    stage: 'Finished, near-finished, or a cesión',
    headline: 'Ready to enjoy from day one — settled in full, or financed.',
    type: 'capital',
    options: [
      ['Pay in full', 'The whole capital, settled at purchase — the cleanest entry into a finished unit or an early investor’s exit (cesión).'],
      ['Or a mortgage', 'For an investment purchase, banks typically ask for 30–50% of the property value as your contribution and finance the rest.'],
    ],
  },
};

// ─── Grading ─────────────────────────────────────────────────────────
const gradeQuiz = (answers) => {
  const totals = { growth: 0, safety: 0, lifestyle: 0 };
  QUIZ_QUESTIONS.forEach((q) => {
    const picked = answers[q.eyebrow] || [];
    q.options.forEach((o) => {
      if (picked.includes(o.id)) {
        Object.entries(o.s).forEach(([k, v]) => { totals[k] += v; });
      }
    });
  });
  const ranked = Object.entries(totals).sort((a, b) => b[1] - a[1]);
  const [topKey, topVal] = ranked[0];
  const secondVal = ranked[1][1];
  const sum = ranked.reduce((a, [, v]) => a + v, 0) || 1;
  const balanced = (topVal - secondVal) <= 1;
  const arch = balanced ? QUIZ_ARCHETYPES.balanced : QUIZ_ARCHETYPES[topKey];
  const match = Math.min(99, Math.max(84, Math.round(72 + (topVal / sum) * 60)));
  return { archetype: arch, totals, match };
};

Object.assign(window, { Glyph, QUIZ_QUESTIONS, QUIZ_ARCHETYPES, QUIZ_FINANCING, gradeQuiz });
