<script>
  import {
    SvelteFlow,
    Controls,
    Background,
    MiniMap,
  } from '@xyflow/svelte';
  import '@xyflow/svelte/dist/style.css';

  // Node styles
  const startNodeStyle = 'background: #c8e6c9; border: 2px solid #2e7d32; border-radius: 25px; padding: 15px 25px; font-weight: bold; font-size: 14px;';
  const decisionNodeStyle = 'background: #fff3e0; border: 2px solid #e65100; border-radius: 8px; padding: 12px 18px; font-weight: 500; font-size: 12px; text-align: center;';
  const testNodeStyle = 'background: #e1f5fe; border: 2px solid #01579b; border-radius: 8px; padding: 12px 20px; font-weight: bold; font-size: 12px; color: #01579b; cursor: pointer;';

  let nodes = $state([
    // Start Node - centered at top
    { id: 'start', position: { x: 500, y: 0 }, data: { label: 'What is your research goal?' }, style: startNodeStyle },

    // Level 1 - main question
    { id: 'q1', position: { x: 450, y: 100 }, data: { label: 'Comparing groups or measuring relationship?' }, style: decisionNodeStyle + ' width: 180px;' },

    // Level 2 - split into comparing groups vs relationship
    { id: 'q2', position: { x: 280, y: 230 }, data: { label: 'How many groups?' }, style: decisionNodeStyle },
    { id: 'q3', position: { x: 820, y: 230 }, data: { label: 'Data type?' }, style: decisionNodeStyle },

    // Level 3 - group comparisons and relationship branches
    { id: 'q4', position: { x: 80, y: 360 }, data: { label: 'Data normal?' }, style: decisionNodeStyle },
    { id: 'q5', position: { x: 280, y: 360 }, data: { label: 'Independent or paired?' }, style: decisionNodeStyle + ' width: 130px;' },
    { id: 'q6', position: { x: 520, y: 360 }, data: { label: 'Data normal?' }, style: decisionNodeStyle },
    { id: 'q11', position: { x: 720, y: 360 }, data: { label: 'Data normal?' }, style: decisionNodeStyle },
    { id: 'q12', position: { x: 920, y: 360 }, data: { label: 'Sample size adequate?' }, style: decisionNodeStyle + ' width: 120px;' },

    // Level 4 - Test results and decisions (left branch: 1 group vs value)
    { id: 't1', position: { x: 20, y: 480 }, data: { label: 'One-Sample T-Test' }, style: testNodeStyle },
    { id: 't2', position: { x: 20, y: 560 }, data: { label: 'Wilcoxon Signed-Rank' }, style: testNodeStyle },

    // Level 4 - Independent/Paired branch
    { id: 'q7', position: { x: 200, y: 480 }, data: { label: 'Data normal?' }, style: decisionNodeStyle },
    { id: 'q8', position: { x: 360, y: 480 }, data: { label: 'Data normal?' }, style: decisionNodeStyle },

    // Level 4 - 3+ groups branch (Data normal? q6 -> Equal variances?)
    { id: 'q10', position: { x: 560, y: 480 }, data: { label: 'Equal variances?' }, style: decisionNodeStyle },
    { id: 't8', position: { x: 700, y: 480 }, data: { label: 'Kruskal-Wallis Test' }, style: testNodeStyle },

    // Level 4 - Correlation branch (below q11 "Data normal?")
    { id: 't11', position: { x: 740, y: 620 }, data: { label: 'Pearson Correlation' }, style: testNodeStyle },
    { id: 't12', position: { x: 890, y: 620 }, data: { label: 'Spearman Correlation' }, style: testNodeStyle },

    // Level 4 - Categorical branch (far right)
    { id: 't13', position: { x: 940, y: 480 }, data: { label: 'Chi-Square Test' }, style: testNodeStyle },
    { id: 't14', position: { x: 1080, y: 480 }, data: { label: "Fisher's Exact Test" }, style: testNodeStyle },

    // Level 5 - Below q7 (Independent -> Data normal?)
    { id: 'q9', position: { x: 150, y: 600 }, data: { label: 'Equal variances?' }, style: decisionNodeStyle },
    { id: 't3', position: { x: 280, y: 600 }, data: { label: 'Mann-Whitney U' }, style: testNodeStyle },

    // Level 5 - Below q8 (Paired -> Data normal?)
    { id: 't6', position: { x: 340, y: 600 }, data: { label: 'Paired T-Test' }, style: testNodeStyle },
    { id: 't7', position: { x: 340, y: 680 }, data: { label: 'Wilcoxon Signed-Rank' }, style: testNodeStyle },

    // Level 5 - ANOVA results (below q10 Equal variances)
    { id: 't9', position: { x: 540, y: 580 }, data: { label: 'One-Way ANOVA' }, style: testNodeStyle },
    { id: 't10', position: { x: 680, y: 580 }, data: { label: "Welch's ANOVA" }, style: testNodeStyle },

    // Level 6 - Final T-tests (below q9 Equal variances)
    { id: 't4', position: { x: 100, y: 720 }, data: { label: 'Independent T-Test' }, style: testNodeStyle },
    { id: 't5', position: { x: 240, y: 720 }, data: { label: "Welch's T-Test" }, style: testNodeStyle },
  ]);

  let edges = $state([
    { id: 'e-start-q1', source: 'start', target: 'q1' },
    { id: 'e-q1-q2', source: 'q1', target: 'q2', label: 'Comparing Groups' },
    { id: 'e-q1-q3', source: 'q1', target: 'q3', label: 'Measuring Relationship' },
    { id: 'e-q2-q4', source: 'q2', target: 'q4', label: '1 group vs value' },
    { id: 'e-q2-q5', source: 'q2', target: 'q5', label: '2 groups' },
    { id: 'e-q2-q6', source: 'q2', target: 'q6', label: '3+ groups' },
    { id: 'e-q3-q11', source: 'q3', target: 'q11', label: 'Both Continuous' },
    { id: 'e-q3-q12', source: 'q3', target: 'q12', label: 'Both Categorical' },
    { id: 'e-q4-t1', source: 'q4', target: 't1', label: 'Yes' },
    { id: 'e-q4-t2', source: 'q4', target: 't2', label: 'No' },
    { id: 'e-q5-q7', source: 'q5', target: 'q7', label: 'Independent' },
    { id: 'e-q5-q8', source: 'q5', target: 'q8', label: 'Paired' },
    { id: 'e-q6-q10', source: 'q6', target: 'q10', label: 'Yes' },
    { id: 'e-q6-t8', source: 'q6', target: 't8', label: 'No' },
    { id: 'e-q7-q9', source: 'q7', target: 'q9', label: 'Yes' },
    { id: 'e-q7-t3', source: 'q7', target: 't3', label: 'No' },
    { id: 'e-q8-t6', source: 'q8', target: 't6', label: 'Yes' },
    { id: 'e-q8-t7', source: 'q8', target: 't7', label: 'No' },
    { id: 'e-q9-t4', source: 'q9', target: 't4', label: 'Yes' },
    { id: 'e-q9-t5', source: 'q9', target: 't5', label: 'No' },
    { id: 'e-q10-t9', source: 'q10', target: 't9', label: 'Yes' },
    { id: 'e-q10-t10', source: 'q10', target: 't10', label: 'No' },
    { id: 'e-q11-t11', source: 'q11', target: 't11', label: 'Yes' },
    { id: 'e-q11-t12', source: 'q11', target: 't12', label: 'No' },
    { id: 'e-q12-t13', source: 'q12', target: 't13', label: 'Yes (freq ≥ 5)' },
    { id: 'e-q12-t14', source: 'q12', target: 't14', label: 'No (small)' },
  ]);

  // Test descriptions
  const testDescriptions = {
    't1': { name: 'One-Sample T-Test', description: 'Compares a sample mean to a known or hypothesized population value.', use: 'Testing if your sample differs from a target value.', example: 'Is the average weight of products equal to 500g specification?', parametric: true },
    't2': { name: 'Wilcoxon Signed-Rank Test', description: 'Non-parametric alternative to one-sample t-test for non-normal data.', use: 'When data is skewed or ordinal.', example: 'Do median satisfaction ratings differ from neutral (3)?', parametric: false },
    't3': { name: 'Mann-Whitney U Test', description: 'Compares distributions of two independent groups without assuming normality.', use: 'Non-parametric alternative to independent t-test.', example: 'Do two groups have different rank distributions?', parametric: false },
    't4': { name: 'Independent T-Test', description: 'Compares means of two independent groups with equal variances.', use: 'Classic comparison of two unrelated groups.', example: 'Do men and women differ in average height?', parametric: true },
    't5': { name: "Welch's T-Test", description: 'Compares means of two groups without assuming equal variances.', use: 'Robust alternative when variances differ.', example: 'Comparing treatment vs control with different variability.', parametric: true },
    't6': { name: 'Paired T-Test', description: 'Compares means of two related measurements (same subjects measured twice).', use: 'Before-after studies, matched pairs.', example: 'Does blood pressure change after medication?', parametric: true },
    't7': { name: 'Wilcoxon Signed-Rank Test', description: 'Non-parametric paired comparison for non-normal data.', use: 'Paired data that violates normality.', example: 'Do rankings improve after training?', parametric: false },
    't8': { name: 'Kruskal-Wallis Test', description: 'Non-parametric comparison of 3+ groups based on ranks.', use: 'Alternative to ANOVA for non-normal data.', example: 'Do satisfaction scores differ across 4 product types?', parametric: false },
    't9': { name: 'One-Way ANOVA', description: 'Compares means across 3 or more groups simultaneously.', use: 'Testing if any group differs from others.', example: 'Do students from different schools perform differently?', parametric: true },
    't10': { name: "Welch's ANOVA", description: 'ANOVA alternative when group variances are unequal.', use: 'Robust multi-group comparison.', example: 'Comparing yields across treatments with different variability.', parametric: true },
    't11': { name: 'Pearson Correlation', description: 'Measures linear relationship strength between two continuous variables.', use: 'Quantifying linear association.', example: 'How strongly are height and weight related?', parametric: true },
    't12': { name: 'Spearman Correlation', description: 'Measures monotonic relationship using ranks, robust to outliers.', use: 'Non-linear but consistent relationships.', example: 'Do income and happiness increase together?', parametric: false },
    't13': { name: 'Chi-Square Test', description: 'Tests independence between two categorical variables.', use: 'Association between categories.', example: 'Is survival rate related to passenger class?', parametric: false },
    't14': { name: "Fisher's Exact Test", description: 'Exact test for categorical association with small samples.', use: 'When expected frequencies are below 5.', example: 'Association in a 2x2 table with few observations.', parametric: false },
  };

  let selectedTest = $state(null);

  function handleNodeClick(event) {
    const nodeId = event.detail.node.id;
    if (nodeId.startsWith('t')) {
      selectedTest = testDescriptions[nodeId];
    } else {
      selectedTest = null;
    }
  }
</script>

<div class="app-container">
  <h1>Statistical Test Decision Flowchart</h1>
  <p class="subtitle">Svelte Version - Click on any blue test node to learn more</p>

  <div class="main-content">
    <div class="flowchart-container">
      <SvelteFlow
        {nodes}
        {edges}
        fitView
        fitViewOptions={{ padding: 0.2, minZoom: 0.5, maxZoom: 1 }}
        minZoom={0.3}
        maxZoom={2}
        onnodeclick={handleNodeClick}
      >
        <Controls />
        <Background variant="dots" gap={12} size={1} />
        <MiniMap />
      </SvelteFlow>
    </div>

    <div class="info-panel">
      {#if selectedTest}
        <div class="test-info">
          <h2>{selectedTest.name}</h2>
          <span class="badge {selectedTest.parametric ? 'parametric' : 'non-parametric'}">
            {selectedTest.parametric ? 'Parametric' : 'Non-Parametric'}
          </span>
          <div class="info-section">
            <h3>Description</h3>
            <p>{selectedTest.description}</p>
          </div>
          <div class="info-section">
            <h3>When to Use</h3>
            <p>{selectedTest.use}</p>
          </div>
          <div class="info-section">
            <h3>Example</h3>
            <p class="example">{selectedTest.example}</p>
          </div>
        </div>
      {:else}
        <div class="placeholder">
          <h2>Select a Test</h2>
          <p>Click on any <span class="highlight">blue test node</span> in the flowchart to see detailed information about that statistical test.</p>

          <div class="legend">
            <h3>Legend</h3>
            <div class="legend-item">
              <div class="legend-box start"></div>
              <span>Start Point</span>
            </div>
            <div class="legend-item">
              <div class="legend-box decision"></div>
              <span>Decision Point</span>
            </div>
            <div class="legend-item">
              <div class="legend-box test"></div>
              <span>Statistical Test</span>
            </div>
          </div>

          <div class="quick-ref">
            <h3>Quick Reference</h3>
            <table>
              <thead>
                <tr>
                  <th>Scenario</th>
                  <th>Parametric</th>
                  <th>Non-Parametric</th>
                </tr>
              </thead>
              <tbody>
                <tr><td>1 sample vs value</td><td>One-Sample T</td><td>Wilcoxon</td></tr>
                <tr><td>2 independent groups</td><td>T-Test / Welch's</td><td>Mann-Whitney U</td></tr>
                <tr><td>2 paired groups</td><td>Paired T-Test</td><td>Wilcoxon</td></tr>
                <tr><td>3+ groups</td><td>ANOVA</td><td>Kruskal-Wallis</td></tr>
                <tr><td>Correlation</td><td>Pearson</td><td>Spearman</td></tr>
                <tr><td>Categorical</td><td>Chi-Square</td><td>Fisher's Exact</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      {/if}
    </div>
  </div>
</div>

<style>
  :global(*) {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }

  :global(body) {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
    background: #f5f5f5;
  }

  .app-container {
    min-height: 100vh;
    padding: 20px;
  }

  h1 {
    text-align: center;
    color: #333;
    margin-bottom: 5px;
    font-size: 28px;
  }

  .subtitle {
    text-align: center;
    color: #666;
    margin-bottom: 20px;
    font-size: 14px;
  }

  .main-content {
    display: flex;
    gap: 20px;
    height: calc(100vh - 120px);
    min-height: 600px;
  }

  .flowchart-container {
    flex: 1;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }

  .info-panel {
    width: 300px;
    min-width: 300px;
    max-width: 300px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 20px;
    overflow-y: auto;
  }

  .test-info h2 {
    color: #01579b;
    margin-bottom: 10px;
    font-size: 22px;
  }

  .badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    margin-bottom: 20px;
  }

  .badge.parametric {
    background: #e8f5e9;
    color: #2e7d32;
  }

  .badge.non-parametric {
    background: #fff3e0;
    color: #e65100;
  }

  .info-section {
    margin-bottom: 20px;
  }

  .info-section h3 {
    color: #555;
    font-size: 14px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 8px;
  }

  .info-section p {
    color: #333;
    line-height: 1.6;
    font-size: 15px;
  }

  .info-section .example {
    background: #f8f9fa;
    padding: 12px;
    border-radius: 8px;
    border-left: 3px solid #01579b;
    font-style: italic;
  }

  .placeholder h2 {
    color: #333;
    margin-bottom: 15px;
  }

  .placeholder > p {
    color: #666;
    line-height: 1.6;
    margin-bottom: 30px;
  }

  .highlight {
    background: #e1f5fe;
    color: #01579b;
    padding: 2px 6px;
    border-radius: 4px;
    font-weight: 500;
  }

  .legend {
    margin-bottom: 30px;
  }

  .legend h3, .quick-ref h3 {
    color: #555;
    font-size: 14px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 12px;
  }

  .legend-item {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 10px;
  }

  .legend-box {
    width: 24px;
    height: 24px;
    border-radius: 4px;
    border: 2px solid;
  }

  .legend-box.start {
    background: #c8e6c9;
    border-color: #2e7d32;
    border-radius: 12px;
  }

  .legend-box.decision {
    background: #fff3e0;
    border-color: #e65100;
  }

  .legend-box.test {
    background: #e1f5fe;
    border-color: #01579b;
  }

  .legend-item span {
    color: #555;
    font-size: 14px;
  }

  .quick-ref table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
  }

  .quick-ref th {
    background: #f5f5f5;
    padding: 8px 6px;
    text-align: left;
    font-weight: 600;
    color: #333;
    border-bottom: 2px solid #ddd;
  }

  .quick-ref td {
    padding: 8px 6px;
    border-bottom: 1px solid #eee;
    color: #555;
  }

  .quick-ref tr:hover td {
    background: #f8f9fa;
  }
</style>
