// ================================================================
// JNM Home Education Program — Lesson Content Seed Script
// ================================================================
// Run:  node seed-lesson-content.js
//
// This script:
//  1. Adds content columns to the lessons table (safe ALTER TABLE)
//  2. Populates every lesson with real instructional content
//  3. Does NOT delete or modify existing data (courses, units, lessons, assignments)
//
// Back up your database before running:
//   pg_dump jnm_homeschool_db > backup_before_lesson_content.sql
// ================================================================

const { Pool } = require('pg');
const dotenv = require('dotenv');
dotenv.config();

const pool = new Pool({
  user: process.env.DB_USER || 'homeschool_user',
  password: process.env.DB_PASSWORD,
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 5432,
  database: process.env.DB_NAME || 'jnm_homeschool_db'
});

// ================================================================
// HELPERS
// ================================================================
function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; }
function rand(a, b) { return Math.floor(Math.random() * (b - a + 1)) + a; }
function has(title, ...words) {
  const t = title.toLowerCase();
  return words.some(w => t.includes(w.toLowerCase()));
}

// ================================================================
// MATH CONTENT
// ================================================================
function mathContent(title, grade, unitTitle) {
  const t = title.toLowerCase();
  const u = (unitTitle || '').toLowerCase();

  // --- objectives ---
  const objectives = [
    `Define and explain the key concepts of ${title}.`,
    `Solve problems involving ${title} with accuracy.`,
    `Apply ${title} strategies to real-world situations.`,
    `Show work and explain reasoning when solving ${title} problems.`,
    `Identify and correct common errors in ${title}.`
  ];

  // --- vocabulary ---
  let vocab = [];
  let content = '';
  let examples = [];
  let practice = [];

  if (has(title, 'addition', 'add', 'sum')) {
    vocab = [
      { term: 'Sum', definition: 'The result of adding two or more numbers together.' },
      { term: 'Addend', definition: 'Any number being added in an addition problem.' },
      { term: 'Carrying (Regrouping)', definition: 'Moving a value to the next place value column when a sum exceeds 9.' },
      { term: 'Commutative Property', definition: 'Changing the order of addends does not change the sum (a + b = b + a).' },
      { term: 'Associative Property', definition: 'Changing the grouping of addends does not change the sum.' },
      { term: 'Identity Property', definition: 'Adding zero to any number gives that same number (a + 0 = a).' }
    ];
    content = `Addition is one of the four basic operations in mathematics. When we add numbers, we combine their values to find a total, called the sum.\n\nTo add numbers, start with the ones place and work left. If a column adds to 10 or more, write the ones digit below the line and carry the tens digit to the next column. This process is called regrouping.\n\nAddition has useful properties. The commutative property tells us that 3 + 5 gives the same result as 5 + 3. The associative property tells us that (2 + 3) + 4 equals 2 + (3 + 4). The identity property tells us that adding zero to any number leaves it unchanged.\n\nWord problems require you to identify what is being combined. Look for clue words like "total," "altogether," "combined," "in all," and "how many more." Set up the addition expression, solve carefully, and check that your answer makes sense in context.`;
    const a1 = rand(10, 99), b1 = rand(10, 99);
    const a2 = rand(100, 999), b2 = rand(100, 999);
    examples = [
      { title: 'Basic Addition', content: `Add ${a1} + ${b1}. Start in the ones place: ${a1 % 10} + ${b1 % 10} = ${(a1 % 10) + (b1 % 10)}. ${(a1 % 10) + (b1 % 10) >= 10 ? 'Since the sum is 10 or more, write ' + ((a1 % 10 + b1 % 10) % 10) + ' and carry 1.' : 'Write ' + ((a1 % 10) + (b1 % 10)) + '.'} Continue to the tens place.`, solution: `${a1} + ${b1} = ${a1 + b1}` },
      { title: 'Word Problem', content: `A library has ${a2} fiction books and ${b2} nonfiction books. How many books does the library have in total? Identify the operation: we are combining two quantities, so we add.`, solution: `${a2} + ${b2} = ${a2 + b2} books` }
    ];
    const p1 = rand(20, 99), p2 = rand(20, 99), p3 = rand(100, 500), p4 = rand(100, 500);
    practice = [
      { question: `Calculate: ${p1} + ${p2}`, hint: 'Start with the ones place. Regroup if the sum exceeds 9.', answer: `${p1 + p2}` },
      { question: `A store sold ${p3} items on Monday and ${p4} items on Tuesday. How many items were sold in total?`, hint: 'Identify the two quantities and add them.', answer: `${p3 + p4} items` }
    ];

  } else if (has(title, 'subtract', 'difference')) {
    vocab = [
      { term: 'Difference', definition: 'The result of subtracting one number from another.' },
      { term: 'Minuend', definition: 'The number being subtracted from (the larger number).' },
      { term: 'Subtrahend', definition: 'The number being subtracted.' },
      { term: 'Borrowing (Regrouping)', definition: 'Taking a value from the next place value column when the top digit is smaller than the bottom digit.' }
    ];
    content = `Subtraction is the operation of finding the difference between two numbers. It tells us how much remains when a quantity is taken away, or how far apart two numbers are.\n\nTo subtract, align the numbers by place value and subtract each column from right to left. If the top digit is smaller than the bottom digit, borrow (regroup) from the next column to the left.\n\nWord problems use clue words like "how many more," "how many fewer," "difference," "remaining," and "left over." Subtraction is the inverse of addition, meaning you can check your answer by adding: if a − b = c, then c + b should equal a.`;
    const a1 = rand(50, 99), b1 = rand(10, a1);
    examples = [
      { title: 'Basic Subtraction', content: `Subtract ${a1} − ${b1}. Ones place: ${a1 % 10} − ${b1 % 10}${a1 % 10 < b1 % 10 ? '. Since ' + (a1 % 10) + ' < ' + (b1 % 10) + ', borrow from the tens place.' : ' = ' + ((a1 % 10) - (b1 % 10)) + '.'}`, solution: `${a1} − ${b1} = ${a1 - b1}` },
      { title: 'Checking with Addition', content: `If 85 − 37 = 48, check by adding: 48 + 37 = 85. ✓ Correct.`, solution: '85 − 37 = 48' }
    ];
    const p1 = rand(50, 200), p2 = rand(10, p1);
    practice = [
      { question: `Calculate: ${p1} − ${p2}`, hint: 'Work right to left. Borrow if needed.', answer: `${p1 - p2}` },
      { question: `Check your answer by adding: does ${p1 - p2} + ${p2} = ${p1}?`, hint: 'Add your answer to the subtrahend.', answer: `Yes, ${p1 - p2} + ${p2} = ${p1}` }
    ];

  } else if (has(title, 'multipl', 'times', 'product')) {
    vocab = [
      { term: 'Product', definition: 'The result of multiplying two or more numbers.' },
      { term: 'Factor', definition: 'A number being multiplied.' },
      { term: 'Commutative Property', definition: 'The order of factors does not change the product (a × b = b × a).' },
      { term: 'Distributive Property', definition: 'a × (b + c) = (a × b) + (a × c).' },
      { term: 'Zero Property', definition: 'Any number multiplied by zero equals zero.' }
    ];
    content = `Multiplication is repeated addition. When we multiply 4 × 3, we are adding 4 three times: 4 + 4 + 4 = 12.\n\nFor multi-digit multiplication, use the standard algorithm: multiply each digit of the bottom number by every digit of the top number, shifting one place left for each row, then add the partial products together.\n\nThe commutative property means 6 × 7 = 7 × 6. The distributive property lets you break apart problems: 8 × 12 = 8 × (10 + 2) = 80 + 16 = 96. These properties make mental math easier.\n\nIn word problems, look for clue words like "each," "every," "per," "times," and "groups of." These signal multiplication.`;
    const a1 = rand(3, 12), b1 = rand(3, 12), a2 = rand(10, 30), b2 = rand(2, 9);
    examples = [
      { title: 'Basic Multiplication', content: `Calculate ${a1} × ${b1}. This means ${a1} groups of ${b1}, or ${b1} added ${a1} times.`, solution: `${a1} × ${b1} = ${a1 * b1}` },
      { title: 'Distributive Property', content: `Calculate ${a2} × ${b2} using the distributive property. Break ${a2} into ${Math.floor(a2/10)*10} + ${a2%10}: (${Math.floor(a2/10)*10} × ${b2}) + (${a2%10} × ${b2}) = ${Math.floor(a2/10)*10*b2} + ${(a2%10)*b2}.`, solution: `${a2} × ${b2} = ${a2 * b2}` }
    ];
    practice = [
      { question: `Calculate: ${rand(4,12)} × ${rand(4,12)}`, hint: 'Multiply using your times tables or repeated addition.', answer: null },
      { question: `A classroom has ${rand(4,8)} rows of desks with ${rand(5,7)} desks in each row. How many desks total?`, hint: 'Multiply rows by desks per row.', answer: null }
    ];

  } else if (has(title, 'divis', 'quotient')) {
    vocab = [
      { term: 'Quotient', definition: 'The result of dividing one number by another.' },
      { term: 'Dividend', definition: 'The number being divided.' },
      { term: 'Divisor', definition: 'The number you are dividing by.' },
      { term: 'Remainder', definition: 'The amount left over when division does not come out evenly.' }
    ];
    content = `Division is the inverse of multiplication. It splits a total into equal groups. When we write 12 ÷ 3 = 4, we are saying 12 can be split into 3 equal groups of 4.\n\nFor long division, follow the steps: Divide, Multiply, Subtract, Bring down (DMSB). Repeat until all digits have been processed. If there is a leftover amount, record it as the remainder.\n\nTo check your work, multiply the quotient by the divisor and add the remainder. The result should equal the dividend. For example: 17 ÷ 5 = 3 remainder 2. Check: 3 × 5 + 2 = 17. ✓`;
    const d1 = rand(2, 9), q1 = rand(5, 15);
    examples = [
      { title: 'Basic Division', content: `Divide ${d1 * q1} ÷ ${d1}. Ask: how many times does ${d1} go into ${d1 * q1}?`, solution: `${d1 * q1} ÷ ${d1} = ${q1}` },
      { title: 'Division with Remainder', content: `Divide ${d1 * q1 + rand(1, d1-1)} ÷ ${d1}. ${d1} goes into the dividend ${q1} times with a remainder.`, solution: `Quotient: ${q1}, Remainder: check your calculation` }
    ];
    practice = [
      { question: `Calculate: ${rand(3,9) * rand(5,12)} ÷ ${rand(3,9)}`, hint: 'Use long division or think about multiplication facts.', answer: null },
      { question: `${rand(20,50)} students need to form equal teams of ${rand(4,8)}. How many full teams can be made?`, hint: 'Divide and look at the whole number quotient.', answer: null }
    ];

  } else if (has(title, 'fract')) {
    vocab = [
      { term: 'Fraction', definition: 'A number representing a part of a whole, written as a/b.' },
      { term: 'Numerator', definition: 'The top number in a fraction; shows how many parts are selected.' },
      { term: 'Denominator', definition: 'The bottom number in a fraction; shows how many equal parts the whole is divided into.' },
      { term: 'Equivalent Fractions', definition: 'Fractions that represent the same value (e.g., 1/2 = 2/4).' },
      { term: 'Improper Fraction', definition: 'A fraction where the numerator is greater than or equal to the denominator.' },
      { term: 'Mixed Number', definition: 'A whole number combined with a fraction (e.g., 2 ½).' }
    ];
    content = `A fraction represents a part of a whole. The denominator tells you how many equal parts the whole is divided into, and the numerator tells you how many of those parts you have.\n\nTo find equivalent fractions, multiply or divide both the numerator and denominator by the same number. For example, 1/3 = 2/6 = 3/9. To simplify a fraction, divide both parts by their greatest common factor.\n\nTo add or subtract fractions, they must have the same denominator (a common denominator). Find the least common denominator, convert each fraction, then add or subtract the numerators. To multiply fractions, multiply numerators together and denominators together. To divide fractions, multiply by the reciprocal of the second fraction.\n\nFractions connect to decimals and percentages. To convert a fraction to a decimal, divide the numerator by the denominator.`;
    examples = [
      { title: 'Equivalent Fractions', content: 'Find a fraction equivalent to 3/4. Multiply both parts by 2: (3×2)/(4×2) = 6/8. So 3/4 = 6/8.', solution: '3/4 = 6/8' },
      { title: 'Adding Fractions', content: 'Add 1/4 + 2/4. The denominators are the same, so add the numerators: (1+2)/4 = 3/4.', solution: '1/4 + 2/4 = 3/4' }
    ];
    practice = [
      { question: 'Simplify the fraction 8/12 to lowest terms.', hint: 'Find the greatest common factor of 8 and 12, then divide both by it.', answer: '2/3' },
      { question: 'Add: 2/5 + 1/5', hint: 'When denominators are the same, add the numerators.', answer: '3/5' }
    ];

  } else if (has(title, 'decimal')) {
    vocab = [
      { term: 'Decimal', definition: 'A number that uses a decimal point to show a value between whole numbers.' },
      { term: 'Tenths', definition: 'The first place to the right of the decimal point (0.1).' },
      { term: 'Hundredths', definition: 'The second place to the right of the decimal point (0.01).' },
      { term: 'Place Value', definition: 'The value of a digit based on its position in the number.' }
    ];
    content = `Decimals are another way to represent parts of a whole, using the base-ten system. The decimal point separates the whole number part from the fractional part. The first digit after the decimal is in the tenths place, the second in the hundredths place, and so on.\n\nTo add or subtract decimals, line up the decimal points and add zeros as placeholders if needed. Then add or subtract as you would with whole numbers. To multiply decimals, multiply as if they were whole numbers, then count the total decimal places in both factors and place the decimal point in the product.\n\nDecimals and fractions are closely related: 0.5 = 1/2, 0.25 = 1/4, 0.75 = 3/4. To convert a fraction to a decimal, divide the numerator by the denominator.`;
    examples = [
      { title: 'Adding Decimals', content: 'Add 3.45 + 2.30. Line up decimal points: 3.45 + 2.30 = 5.75.', solution: '3.45 + 2.30 = 5.75' },
      { title: 'Decimal to Fraction', content: 'Convert 0.6 to a fraction. 0.6 = 6/10 = 3/5.', solution: '0.6 = 3/5' }
    ];
    practice = [
      { question: 'Calculate: 4.56 + 1.23', hint: 'Line up the decimal points and add column by column.', answer: '5.79' },
      { question: 'Convert 3/4 to a decimal.', hint: 'Divide 3 by 4.', answer: '0.75' }
    ];

  } else if (has(title, 'percent')) {
    vocab = [
      { term: 'Percent', definition: 'A ratio that compares a number to 100. The symbol % means "per hundred."' },
      { term: 'Proportion', definition: 'An equation stating that two ratios are equal.' }
    ];
    content = `Percent means "per hundred." So 45% means 45 out of 100. Percentages are used everywhere: sales tax, discounts, test scores, statistics, and tips.\n\nTo convert a percent to a decimal, divide by 100 (move the decimal point two places left): 75% = 0.75. To convert a decimal to a percent, multiply by 100: 0.3 = 30%. To find a percent of a number, convert the percent to a decimal and multiply: 20% of 150 = 0.20 × 150 = 30.\n\nPercent increase and decrease problems compare the change to the original amount: Percent Change = (Change ÷ Original) × 100.`;
    const orig = rand(2, 10) * 50;
    examples = [
      { title: 'Finding a Percentage', content: `What is 25% of ${orig}? Convert: 25% = 0.25. Multiply: 0.25 × ${orig} = ${0.25 * orig}.`, solution: `25% of ${orig} = ${0.25 * orig}` },
      { title: 'Percent to Decimal', content: 'Convert 68% to a decimal. Move the decimal two places left: 68% = 0.68.', solution: '68% = 0.68' }
    ];
    practice = [
      { question: `What is 15% of ${rand(5,20)*20}?`, hint: 'Convert 15% to 0.15, then multiply.', answer: null },
      { question: 'A shirt was $40 and is now $30. What is the percent decrease?', hint: 'Change = 40 − 30 = 10. Percent = (10 ÷ 40) × 100.', answer: '25%' }
    ];

  } else if (has(title, 'equation', 'variable', 'expression', 'algebra', 'solve')) {
    vocab = [
      { term: 'Variable', definition: 'A letter or symbol that represents an unknown value.' },
      { term: 'Expression', definition: 'A mathematical phrase containing numbers, variables, and operations (no equals sign).' },
      { term: 'Equation', definition: 'A mathematical statement that two expressions are equal (has an equals sign).' },
      { term: 'Coefficient', definition: 'The number multiplied by a variable (in 3x, the coefficient is 3).' },
      { term: 'Constant', definition: 'A fixed number with no variable attached.' },
      { term: 'Inverse Operation', definition: 'An operation that undoes another (addition undoes subtraction, multiplication undoes division).' }
    ];
    content = `An equation is a statement that two expressions are equal, like 2x + 3 = 11. Solving an equation means finding the value of the variable that makes the statement true.\n\nTo solve, use inverse operations to isolate the variable. Whatever you do to one side, you must do to the other side to maintain balance. For 2x + 3 = 11: subtract 3 from both sides to get 2x = 8, then divide both sides by 2 to get x = 4.\n\nAlways check your solution by substituting it back into the original equation: 2(4) + 3 = 8 + 3 = 11. ✓\n\nExpressions can be simplified by combining like terms. Like terms have the same variable raised to the same power. For example, 3x + 5x = 8x, but 3x + 5x² cannot be combined because x and x² are different.`;
    const a = rand(2, 8), b = rand(1, 10), x = rand(2, 10);
    examples = [
      { title: 'One-Step Equation', content: `Solve: ${a}x = ${a * x}. Divide both sides by ${a}.`, solution: `x = ${x}` },
      { title: 'Two-Step Equation', content: `Solve: ${a}x + ${b} = ${a * x + b}. Step 1: Subtract ${b} from both sides → ${a}x = ${a * x}. Step 2: Divide by ${a}.`, solution: `x = ${x}` }
    ];
    practice = [
      { question: `Solve: 3x + 7 = 22`, hint: 'Subtract 7 from both sides, then divide by 3.', answer: 'x = 5' },
      { question: `Simplify: 4x + 2x − 3`, hint: 'Combine like terms (the x terms).', answer: '6x − 3' }
    ];

  } else if (has(title, 'geometry', 'shape', 'area', 'perimeter', 'volume', 'angle', 'triangle', 'circle')) {
    vocab = [
      { term: 'Perimeter', definition: 'The total distance around the outside of a shape.' },
      { term: 'Area', definition: 'The amount of space inside a two-dimensional shape, measured in square units.' },
      { term: 'Volume', definition: 'The amount of space inside a three-dimensional shape, measured in cubic units.' },
      { term: 'Radius', definition: 'The distance from the center of a circle to its edge.' },
      { term: 'Diameter', definition: 'The distance across a circle through its center; equal to 2 × radius.' },
      { term: 'Vertex', definition: 'A point where two sides of a shape meet (corner).' }
    ];
    content = `Geometry is the study of shapes, sizes, and spatial relationships. Two-dimensional shapes have length and width. Three-dimensional shapes also have depth.\n\nPerimeter is the distance around a shape. For a rectangle, P = 2(length + width). Area is the space inside a shape. For a rectangle, A = length × width. For a triangle, A = ½ × base × height. For a circle, A = π × r².\n\nVolume measures the space inside a 3D shape. For a rectangular prism (box), V = length × width × height. For a cylinder, V = π × r² × height.\n\nAngles are measured in degrees. A right angle is 90°, a straight angle is 180°, and a full rotation is 360°. The angles in any triangle always add up to 180°.`;
    const l = rand(5, 15), w = rand(3, 10);
    examples = [
      { title: 'Area of a Rectangle', content: `Find the area of a rectangle with length ${l} cm and width ${w} cm. Area = length × width.`, solution: `A = ${l} × ${w} = ${l * w} cm²` },
      { title: 'Perimeter of a Rectangle', content: `Find the perimeter of the same rectangle. P = 2(length + width).`, solution: `P = 2(${l} + ${w}) = 2(${l + w}) = ${2 * (l + w)} cm` }
    ];
    practice = [
      { question: `Find the area of a triangle with base ${rand(6,14)} and height ${rand(4,10)}.`, hint: 'A = ½ × base × height.', answer: null },
      { question: 'Find the circumference of a circle with radius 7. Use π ≈ 3.14.', hint: 'C = 2πr.', answer: '43.96' }
    ];

  } else if (has(title, 'ratio', 'proportion', 'rate')) {
    vocab = [
      { term: 'Ratio', definition: 'A comparison of two quantities (e.g., 3:5 or 3/5).' },
      { term: 'Proportion', definition: 'An equation showing two ratios are equal (a/b = c/d).' },
      { term: 'Unit Rate', definition: 'A rate with a denominator of 1 (e.g., $3 per hour).' },
      { term: 'Cross-Multiply', definition: 'A method for solving proportions: a/b = c/d means a × d = b × c.' }
    ];
    content = `A ratio compares two quantities. It can be written as a:b, a/b, or "a to b." Ratios can be simplified just like fractions by dividing both parts by their greatest common factor.\n\nA proportion states that two ratios are equal. To solve a proportion like x/4 = 6/8, cross-multiply: 8x = 24, so x = 3. You can also think of it as scaling: 6/8 simplifies to 3/4, so x = 3.\n\nA unit rate expresses a ratio with a denominator of 1. If you drive 150 miles in 3 hours, the unit rate is 150 ÷ 3 = 50 miles per hour. Unit rates make it easy to compare options.`;
    examples = [
      { title: 'Simplifying a Ratio', content: 'Simplify 12:8. The GCF of 12 and 8 is 4. Divide both by 4: 12:8 = 3:2.', solution: '12:8 = 3:2' },
      { title: 'Solving a Proportion', content: 'Solve: x/5 = 12/20. Cross multiply: 20x = 60. Divide: x = 3.', solution: 'x = 3' }
    ];
    practice = [
      { question: 'Simplify the ratio 18:12.', hint: 'Find the GCF and divide both by it.', answer: '3:2' },
      { question: 'If 4 notebooks cost $6, how much do 10 notebooks cost?', hint: 'Set up a proportion: 4/6 = 10/x, then cross-multiply.', answer: '$15' }
    ];

  } else if (has(title, 'function', 'domain', 'range', 'slope', 'linear', 'graph', 'intercept')) {
    vocab = [
      { term: 'Function', definition: 'A rule that assigns exactly one output to each input.' },
      { term: 'Domain', definition: 'The set of all possible input values (x-values).' },
      { term: 'Range', definition: 'The set of all possible output values (y-values).' },
      { term: 'Slope', definition: 'The steepness of a line; rise over run; m = (y₂ − y₁)/(x₂ − x₁).' },
      { term: 'Y-intercept', definition: 'The point where a line crosses the y-axis (where x = 0).' },
      { term: 'Slope-Intercept Form', definition: 'y = mx + b, where m is slope and b is the y-intercept.' }
    ];
    content = `A function is a mathematical relationship where each input produces exactly one output. We write f(x) = 2x + 3 to define a function. If x = 4, then f(4) = 2(4) + 3 = 11.\n\nLinear functions produce straight lines when graphed. The equation y = mx + b is called slope-intercept form. The slope (m) describes how steep the line is, and the y-intercept (b) tells where the line crosses the y-axis.\n\nTo find slope between two points (x₁, y₁) and (x₂, y₂), use m = (y₂ − y₁)/(x₂ − x₁). A positive slope means the line rises from left to right. A negative slope means it falls. A slope of zero is a horizontal line.\n\nThe domain is all valid inputs, and the range is all valid outputs. For most linear functions, both the domain and range include all real numbers.`;
    examples = [
      { title: 'Finding Slope', content: 'Find the slope between (1, 3) and (4, 9). m = (9 − 3)/(4 − 1) = 6/3.', solution: 'm = 2' },
      { title: 'Evaluating a Function', content: 'If f(x) = 3x − 5, find f(4). Substitute: f(4) = 3(4) − 5 = 12 − 5.', solution: 'f(4) = 7' }
    ];
    practice = [
      { question: 'Find the slope of the line passing through (2, 5) and (6, 13).', hint: 'Use m = (y₂ − y₁)/(x₂ − x₁).', answer: 'm = 2' },
      { question: 'Write the equation of a line with slope 3 and y-intercept −2.', hint: 'Use slope-intercept form: y = mx + b.', answer: 'y = 3x − 2' }
    ];

  } else if (has(title, 'quadratic', 'parabola', 'factor', 'polynom')) {
    vocab = [
      { term: 'Quadratic Equation', definition: 'An equation of the form ax² + bx + c = 0.' },
      { term: 'Parabola', definition: 'The U-shaped curve produced by graphing a quadratic function.' },
      { term: 'Vertex', definition: 'The highest or lowest point of a parabola.' },
      { term: 'Factoring', definition: 'Rewriting an expression as a product of simpler expressions.' },
      { term: 'Quadratic Formula', definition: 'x = (−b ± √(b² − 4ac)) / 2a, used to solve any quadratic equation.' }
    ];
    content = `A quadratic equation has the form ax² + bx + c = 0. Its graph is a parabola — a U-shaped curve that opens upward (when a > 0) or downward (when a < 0).\n\nThere are three main methods for solving quadratic equations: factoring, completing the square, and the quadratic formula. Factoring works when the expression can be written as a product of two binomials. For example, x² − 5x + 6 = (x − 2)(x − 3), giving solutions x = 2 and x = 3.\n\nThe quadratic formula x = (−b ± √(b² − 4ac)) / 2a works for any quadratic equation. The discriminant (b² − 4ac) tells you how many real solutions exist: positive means two solutions, zero means one, negative means no real solutions.\n\nThe vertex of the parabola is at x = −b/(2a). This gives the maximum or minimum value of the function.`;
    examples = [
      { title: 'Factoring', content: 'Solve x² − 7x + 12 = 0. Find two numbers that multiply to 12 and add to −7: −3 and −4. Factor: (x − 3)(x − 4) = 0.', solution: 'x = 3 or x = 4' },
      { title: 'Quadratic Formula', content: 'Solve 2x² + 3x − 2 = 0. a=2, b=3, c=−2. Discriminant = 9 + 16 = 25. x = (−3 ± 5)/4.', solution: 'x = 1/2 or x = −2' }
    ];
    practice = [
      { question: 'Factor and solve: x² − 9x + 20 = 0', hint: 'Find two numbers that multiply to 20 and add to −9.', answer: 'x = 4 or x = 5' },
      { question: 'Use the quadratic formula to solve: x² + 2x − 8 = 0', hint: 'a=1, b=2, c=−8. Plug into the formula.', answer: 'x = 2 or x = −4' }
    ];

  } else if (has(title, 'trigon', 'sin', 'cos', 'tan')) {
    vocab = [
      { term: 'Sine (sin)', definition: 'In a right triangle, sin(θ) = opposite side / hypotenuse.' },
      { term: 'Cosine (cos)', definition: 'In a right triangle, cos(θ) = adjacent side / hypotenuse.' },
      { term: 'Tangent (tan)', definition: 'In a right triangle, tan(θ) = opposite side / adjacent side.' },
      { term: 'Hypotenuse', definition: 'The longest side of a right triangle, opposite the right angle.' },
      { term: 'SOH CAH TOA', definition: 'Memory aid: Sine=Opposite/Hypotenuse, Cosine=Adjacent/Hypotenuse, Tangent=Opposite/Adjacent.' }
    ];
    content = `Trigonometry studies the relationships between angles and sides of triangles. The three primary trigonometric ratios — sine, cosine, and tangent — relate an angle in a right triangle to ratios of its sides.\n\nThe mnemonic SOH CAH TOA helps you remember: Sine = Opposite/Hypotenuse, Cosine = Adjacent/Hypotenuse, Tangent = Opposite/Adjacent.\n\nTrigonometric functions also apply to the unit circle, where any angle θ maps to coordinates (cos θ, sin θ). This extends trigonometry beyond right triangles to all angles, including those greater than 90°.\n\nCommon angle values to memorize: sin(30°) = 1/2, sin(45°) = √2/2, sin(60°) = √3/2, cos(30°) = √3/2, cos(45°) = √2/2, cos(60°) = 1/2.`;
    examples = [
      { title: 'Finding a Side', content: 'In a right triangle with angle 30° and hypotenuse 10, find the opposite side. sin(30°) = opposite/10, so opposite = 10 × sin(30°) = 10 × 0.5.', solution: 'opposite = 5' },
      { title: 'Finding an Angle', content: 'A right triangle has opposite side 4 and adjacent side 3. Find angle θ. tan(θ) = 4/3 ≈ 1.333. θ = arctan(1.333).', solution: 'θ ≈ 53.1°' }
    ];
    practice = [
      { question: 'Find the missing side: right triangle, angle 45°, hypotenuse 8. Find opposite.', hint: 'sin(45°) = opposite/8. sin(45°) ≈ 0.707.', answer: '≈ 5.66' },
      { question: 'What is cos(60°)?', hint: 'Recall the common angle values or use the unit circle.', answer: '0.5' }
    ];

  } else if (has(title, 'statist', 'data', 'mean', 'median', 'probab')) {
    vocab = [
      { term: 'Mean', definition: 'The average; sum of all values divided by the count.' },
      { term: 'Median', definition: 'The middle value when data is ordered from least to greatest.' },
      { term: 'Mode', definition: 'The value that appears most frequently in a data set.' },
      { term: 'Range', definition: 'The difference between the highest and lowest values.' },
      { term: 'Probability', definition: 'The likelihood of an event occurring, expressed as a number between 0 and 1.' }
    ];
    content = `Statistics is the study of collecting, organizing, and interpreting data. The three most common measures of central tendency are mean, median, and mode.\n\nThe mean (average) is found by adding all values and dividing by how many there are. The median is the middle value when data is sorted — if there is an even number of values, average the two middle ones. The mode is the most frequent value.\n\nProbability measures how likely something is to happen. P(event) = favorable outcomes / total outcomes. A probability of 0 means impossible, 1 means certain. The probability of flipping heads on a fair coin is 1/2 = 0.5 = 50%.`;
    examples = [
      { title: 'Finding the Mean', content: 'Data: 8, 5, 12, 9, 6. Sum = 40. Count = 5. Mean = 40 ÷ 5.', solution: 'Mean = 8' },
      { title: 'Finding Probability', content: 'A bag has 3 red and 7 blue marbles. P(red) = 3/(3+7) = 3/10.', solution: 'P(red) = 0.3 = 30%' }
    ];
    practice = [
      { question: 'Find the median of: 14, 7, 11, 3, 9', hint: 'First sort the numbers, then find the middle one.', answer: '9' },
      { question: 'A die has 6 faces. What is the probability of rolling a number less than 3?', hint: 'Count favorable outcomes (1 and 2) out of total (6).', answer: '2/6 = 1/3' }
    ];

  } else {
    // Generic math content
    vocab = [
      { term: 'Operation', definition: 'A mathematical process such as addition, subtraction, multiplication, or division.' },
      { term: 'Expression', definition: 'A combination of numbers, variables, and operations.' },
      { term: 'Equation', definition: 'A mathematical statement that two expressions are equal.' },
      { term: 'Solution', definition: 'A value that makes an equation true.' }
    ];
    content = `This lesson covers important mathematical concepts related to ${title}. Mathematics builds step by step — each new skill relies on understanding previous concepts.\n\nWhen approaching ${title}, start by identifying what you know and what you need to find. Choose the appropriate operation or strategy, show your work step by step, and check your answer.\n\nProblem-solving involves understanding the question, planning your approach, executing your plan, and verifying the result. Always label your answers with appropriate units and check that your solution makes sense in the context of the problem.`;
    examples = [
      { title: 'Applying Concepts', content: `Apply the methods from this lesson to solve a problem involving ${title}. Identify the key information, set up your work, and solve step by step.`, solution: 'Verify your answer by substituting back or using a different method.' }
    ];
    practice = [
      { question: `Solve a problem related to ${title} using the methods from this lesson.`, hint: 'Review the examples above and follow the same process.', answer: null }
    ];
  }

  return { objectives, content, vocabulary: vocab, examples, practice };
}

// ================================================================
// LANGUAGE ARTS CONTENT
// ================================================================
function elaContent(title, grade, unitTitle) {
  const t = title.toLowerCase();
  let objectives, content, vocab, examples, practice;

  objectives = [
    `Identify and explain key concepts related to ${title}.`,
    `Apply reading and writing strategies to ${title} tasks.`,
    `Analyze texts and examples connected to ${title}.`,
    `Use evidence from texts to support your ideas.`,
    `Strengthen vocabulary and language skills through ${title}.`
  ];

  if (has(title, 'reading', 'comprehen', 'passage')) {
    vocab = [
      { term: 'Main Idea', definition: 'The central point or message of a text.' },
      { term: 'Supporting Details', definition: 'Facts, examples, or descriptions that back up the main idea.' },
      { term: 'Inference', definition: 'A conclusion drawn from evidence and reasoning, not stated directly.' },
      { term: 'Context Clues', definition: 'Words or phrases surrounding an unfamiliar word that help reveal its meaning.' },
      { term: 'Summary', definition: 'A brief restatement of the most important points of a text.' },
      { term: 'Author\'s Purpose', definition: 'The reason an author writes: to inform, persuade, entertain, or explain.' }
    ];
    content = `Reading comprehension means understanding what you read — not just the words, but the meaning behind them. Strong readers actively engage with text by asking questions, making predictions, and connecting what they read to what they already know.\n\nThe main idea is what the text is mostly about. Supporting details are the facts, examples, and descriptions that explain or prove the main idea. To find the main idea, ask: "What is the author mostly telling me?"\n\nMaking inferences means reading between the lines. Authors do not always state everything directly. Use clues from the text plus your own knowledge to draw conclusions. For example, if a character puts on a coat and grabs an umbrella, you can infer it is cold and rainy outside.\n\nWhen you encounter unfamiliar words, use context clues — the surrounding words and sentences — to figure out the meaning. Look for definitions, examples, synonyms, or antonyms nearby.`;
    examples = [
      { title: 'Finding the Main Idea', content: 'Read this passage: "Bees are essential pollinators. They carry pollen from flower to flower, helping plants reproduce. Without bees, many fruits and vegetables would not grow." The main idea is that bees play a vital role in plant reproduction.', solution: 'Main idea: Bees are essential pollinators that help plants reproduce.' },
      { title: 'Making an Inference', content: 'The passage says: "Maria checked her watch again and tapped her foot." What can you infer? Maria is probably waiting for someone or something and feels impatient.', solution: 'Inference: Maria is impatient about waiting.' }
    ];
    practice = [
      { question: 'Read a paragraph from your current text. Identify the main idea in one sentence and list two supporting details.', hint: 'Ask yourself: What is this paragraph mostly about? What facts support that?', answer: null },
      { question: 'Find a word you do not know in your reading. Use context clues to determine its meaning, then check a dictionary.', hint: 'Look at the sentences around the unknown word for hints.', answer: null }
    ];

  } else if (has(title, 'grammar', 'sentence', 'punctuat', 'parts of speech')) {
    vocab = [
      { term: 'Noun', definition: 'A word that names a person, place, thing, or idea.' },
      { term: 'Verb', definition: 'A word that shows action or a state of being.' },
      { term: 'Adjective', definition: 'A word that describes or modifies a noun.' },
      { term: 'Adverb', definition: 'A word that describes a verb, adjective, or another adverb (often ends in -ly).' },
      { term: 'Subject', definition: 'The person, place, or thing that performs the action in a sentence.' },
      { term: 'Predicate', definition: 'The part of the sentence that tells what the subject does or is.' }
    ];
    content = `Every sentence has two essential parts: a subject (who or what the sentence is about) and a predicate (what the subject does or is). A complete sentence expresses a complete thought.\n\nThe eight parts of speech are nouns, pronouns, verbs, adjectives, adverbs, prepositions, conjunctions, and interjections. Understanding these helps you construct clear, correct sentences.\n\nProper punctuation helps readers understand your writing. Periods end statements, question marks end questions, and exclamation marks show strong feeling. Commas separate items in a list, join independent clauses with conjunctions, and set off introductory elements.\n\nSubject-verb agreement means the verb must match the subject in number: "The dog runs" (singular) vs. "The dogs run" (plural).`;
    examples = [
      { title: 'Identifying Parts of Speech', content: '"The brave firefighter quickly climbed the tall ladder." Noun: firefighter, ladder. Verb: climbed. Adjective: brave, tall. Adverb: quickly.', solution: 'Each word serves a specific function in the sentence.' },
      { title: 'Correcting a Sentence', content: 'Incorrect: "Me and him went to the store." Correct: "He and I went to the store." Use subject pronouns (I, he, she, we, they) as subjects.', solution: '"He and I went to the store."' }
    ];
    practice = [
      { question: 'Identify the subject and predicate in: "The old oak tree swayed gently in the wind."', hint: 'The subject is who/what the sentence is about. The predicate is everything else.', answer: 'Subject: The old oak tree. Predicate: swayed gently in the wind.' },
      { question: 'Add commas where needed: "I need eggs milk bread and butter from the store."', hint: 'Use commas to separate items in a list.', answer: '"I need eggs, milk, bread, and butter from the store."' }
    ];

  } else if (has(title, 'writing', 'essay', 'composit', 'paragraph', 'narrative', 'persuasi', 'argument')) {
    vocab = [
      { term: 'Thesis Statement', definition: 'A sentence that states the main argument or point of an essay.' },
      { term: 'Topic Sentence', definition: 'The first sentence of a paragraph that introduces its main idea.' },
      { term: 'Supporting Evidence', definition: 'Facts, quotes, or examples that prove your point.' },
      { term: 'Transition', definition: 'A word or phrase that connects ideas between sentences or paragraphs.' },
      { term: 'Conclusion', definition: 'The final paragraph that summarizes the main points and restates the thesis.' },
      { term: 'Hook', definition: 'An opening sentence designed to grab the reader\'s attention.' }
    ];
    content = `Strong writing follows a clear structure: introduction, body paragraphs, and conclusion. The introduction opens with a hook to catch the reader's attention, provides background context, and ends with a thesis statement that presents your main argument.\n\nEach body paragraph should begin with a topic sentence, followed by evidence or examples, and an explanation of how the evidence supports your thesis. Use transitions like "furthermore," "in contrast," "for example," and "as a result" to connect ideas smoothly.\n\nThe conclusion restates the thesis in new words, summarizes key points, and leaves the reader with a final thought. Never introduce new evidence in the conclusion.\n\nRevision is essential. After drafting, re-read for clarity, organization, evidence, grammar, and spelling. Reading aloud helps catch awkward phrasing and errors.`;
    examples = [
      { title: 'Writing a Thesis Statement', content: 'Topic: school uniforms. Weak thesis: "School uniforms are good." Strong thesis: "School uniforms reduce peer pressure, decrease morning decision fatigue, and promote a sense of community among students."', solution: 'A strong thesis is specific and lists the main points you will discuss.' },
      { title: 'Using Transitions', content: 'Without transition: "Exercise improves mood. It strengthens muscles." With transition: "Exercise improves mood. Additionally, it strengthens muscles."', solution: 'Transitions create smooth connections between ideas.' }
    ];
    practice = [
      { question: 'Write a thesis statement for an essay about the importance of reading.', hint: 'State your position and include 2-3 reasons you will discuss.', answer: null },
      { question: 'Write a body paragraph with a topic sentence, two pieces of evidence, and a concluding sentence.', hint: 'Start with your point, support it with facts or examples, then wrap up.', answer: null }
    ];

  } else if (has(title, 'vocab', 'word', 'spelling')) {
    vocab = [
      { term: 'Synonym', definition: 'A word with a similar meaning to another word (e.g., happy and joyful).' },
      { term: 'Antonym', definition: 'A word with the opposite meaning (e.g., hot and cold).' },
      { term: 'Root Word', definition: 'The base part of a word that carries the core meaning.' },
      { term: 'Prefix', definition: 'A letter group added to the beginning of a word to change its meaning (e.g., un-, re-, pre-).' },
      { term: 'Suffix', definition: 'A letter group added to the end of a word (e.g., -tion, -ly, -ful).' },
      { term: 'Homophone', definition: 'Words that sound the same but have different meanings and spellings (e.g., their/there/they\'re).' }
    ];
    content = `Building a strong vocabulary improves reading comprehension, writing quality, and communication skills. There are several strategies for learning new words.\n\nWord parts (prefixes, roots, and suffixes) help you decode unfamiliar words. The prefix "un-" means "not" (unhappy = not happy). The root "duct" means "to lead" (conduct, produce). The suffix "-tion" turns a verb into a noun (celebrate → celebration).\n\nContext clues help you figure out word meanings while reading. Look for definitions, examples, comparisons, or contrasts near the unknown word.\n\nTo improve spelling, practice writing words, break them into syllables, and look for patterns. Many spelling rules have patterns: "i before e except after c," double the final consonant before adding -ing to short vowel words (run → running).`;
    examples = [
      { title: 'Using Word Parts', content: '"Unbelievable" = un (not) + believe + able (capable of). Meaning: not capable of being believed; incredible.', solution: 'unbelievable = not capable of being believed' },
      { title: 'Context Clues', content: '"The arid desert received less than five inches of rain per year." Clue: "less than five inches of rain" tells us arid means very dry.', solution: 'arid = extremely dry' }
    ];
    practice = [
      { question: 'Break the word "disagreement" into its prefix, root, and suffix. Define each part.', hint: 'dis- (not) + agree (to be in harmony) + -ment (state of).', answer: 'dis-agree-ment: the state of not agreeing' },
      { question: 'Write the correct homophone: "They went (their/there/they\'re) to pick up (their/there/they\'re) order."', hint: '"There" = a place. "Their" = belonging to them. "They\'re" = they are.', answer: 'They went there to pick up their order.' }
    ];

  } else if (has(title, 'poetry', 'poem', 'literary', 'literature', 'fiction', 'novel', 'story', 'short stor', 'drama')) {
    vocab = [
      { term: 'Theme', definition: 'The underlying message or central idea of a literary work.' },
      { term: 'Symbolism', definition: 'Using objects, characters, or events to represent abstract ideas.' },
      { term: 'Metaphor', definition: 'A comparison between two unlike things without using "like" or "as."' },
      { term: 'Simile', definition: 'A comparison using "like" or "as" (e.g., "fast as lightning").' },
      { term: 'Tone', definition: 'The author\'s attitude toward the subject matter.' },
      { term: 'Characterization', definition: 'How an author develops and reveals a character\'s personality.' },
      { term: 'Conflict', definition: 'The struggle between opposing forces that drives the plot.' },
      { term: 'Foreshadowing', definition: 'Hints or clues about events that will happen later in the story.' }
    ];
    content = `Literature allows us to explore human experiences, emotions, and ideas through storytelling. When analyzing literature, look at several key elements.\n\nCharacterization is how an author reveals a character — through their actions, words, thoughts, appearance, and what others say about them. Dynamic characters change over the course of the story, while static characters remain the same.\n\nConflict drives the plot forward. Internal conflict occurs within a character (a difficult decision). External conflict occurs between a character and an outside force (nature, society, another character).\n\nTheme is the deeper message the author wants to convey. It is not a topic (like "love") but a statement about that topic (like "true love requires sacrifice"). To identify theme, look at what characters learn and how conflicts resolve.\n\nLiterary devices like metaphor, simile, symbolism, and foreshadowing add layers of meaning. Recognizing these enriches your understanding of the text.`;
    examples = [
      { title: 'Identifying Theme', content: 'In a story where a shy student finds courage to speak up against bullying, the theme might be: "Standing up for what is right requires courage, but it inspires others to do the same."', solution: 'Theme = a message about life, not just a topic word.' },
      { title: 'Analyzing Characterization', content: 'The author writes: "Jake straightened his shoulders, took a deep breath, and walked into the room full of strangers." This shows Jake is nervous but determined — revealed through his actions.', solution: 'Indirect characterization through actions.' }
    ];
    practice = [
      { question: 'Choose a character from your current reading. Describe how the author reveals their personality using at least two methods of characterization.', hint: 'Consider: what do they say? What do they do? What do others say about them?', answer: null },
      { question: 'Identify one example of figurative language (simile, metaphor, or symbolism) in your reading and explain what it means.', hint: 'Look for comparisons or objects that seem to represent something larger.', answer: null }
    ];

  } else if (has(title, 'rhetoric', 'persuasi', 'argument', 'speech', 'debate')) {
    vocab = [
      { term: 'Ethos', definition: 'A persuasive appeal based on the credibility or authority of the speaker.' },
      { term: 'Pathos', definition: 'A persuasive appeal to the audience\'s emotions.' },
      { term: 'Logos', definition: 'A persuasive appeal based on logic, evidence, and reasoning.' },
      { term: 'Claim', definition: 'The main argument or position being made.' },
      { term: 'Counterclaim', definition: 'An opposing argument that challenges the claim.' },
      { term: 'Rebuttal', definition: 'A response that disproves or weakens a counterclaim.' }
    ];
    content = `Rhetoric is the art of effective communication and persuasion. Since ancient Greece, speakers and writers have used three main appeals to persuade their audiences.\n\nEthos establishes the speaker's credibility. A doctor discussing medicine has built-in ethos through expertise. Writers build ethos by demonstrating knowledge, fairness, and good character.\n\nPathos appeals to emotions — empathy, fear, pride, anger, or hope. Storytelling and vivid language create emotional connections. However, relying only on pathos without evidence weakens an argument.\n\nLogos uses logic, data, and evidence. Statistics, research studies, and logical reasoning build a case that is hard to refute. The strongest arguments combine all three appeals.\n\nEffective argumentation also addresses counterclaims. Acknowledging and rebutting opposing viewpoints shows fairness and strengthens your position.`;
    examples = [
      { title: 'Identifying Appeals', content: '"As a 20-year veteran teacher (ethos), I have seen countless students struggle with overcrowded classrooms (pathos). Studies show that reducing class size by 30% improves test scores by 15% (logos)."', solution: 'This passage uses all three rhetorical appeals.' },
      { title: 'Addressing a Counterclaim', content: 'Claim: Schools should start later. Counterclaim: Later starts conflict with parents\' work schedules. Rebuttal: Adjusted bus routes and before-school programs can accommodate working families.', solution: 'Acknowledging and responding to opposition strengthens the argument.' }
    ];
    practice = [
      { question: 'Write a short persuasive paragraph using at least one example of ethos, pathos, and logos.', hint: 'Start with your claim, then support it with credibility, emotion, and evidence.', answer: null },
      { question: 'Identify the rhetorical appeal (ethos, pathos, or logos) in this statement: "Nine out of ten dentists recommend this toothpaste."', hint: 'What kind of evidence is this — emotional, credibility-based, or logical?', answer: 'Ethos (appeal to expert authority) and Logos (statistical evidence).' }
    ];

  } else {
    vocab = [
      { term: 'Analysis', definition: 'Detailed examination of the elements or structure of something.' },
      { term: 'Evidence', definition: 'Information used to support a claim or argument.' },
      { term: 'Perspective', definition: 'A particular attitude toward or way of regarding something; point of view.' }
    ];
    content = `This lesson focuses on developing your language arts skills through the study of ${title}. Strong readers and writers share a set of core practices: they read actively, think critically, and communicate clearly.\n\nActive reading means engaging with the text by highlighting key ideas, asking questions, making connections, and summarizing in your own words. Critical thinking means evaluating arguments, recognizing bias, and forming your own well-supported opinions.\n\nWhen writing about what you read, always support your ideas with evidence from the text. Use direct references and explain how the evidence connects to your point. This strengthens your analysis and makes your writing more convincing.`;
    examples = [
      { title: 'Textual Evidence', content: `When making a claim about a text, support it with a specific reference: "The author suggests that persistence matters, as shown when the character states, 'I won't give up no matter what.'"`, solution: 'Always connect your evidence back to your main point.' }
    ];
    practice = [
      { question: `Based on your study of ${title}, write a response that includes a claim, evidence from the text, and an explanation.`, hint: 'Claim → Evidence → Explanation. This is the C-E-E structure.', answer: null }
    ];
  }

  return { objectives, content, vocabulary: vocab, examples, practice };
}

// ================================================================
// SCIENCE CONTENT
// ================================================================
function scienceContent(title, grade, unitTitle) {
  let objectives, content, vocab, examples, practice;

  objectives = [
    `Explain the key scientific concepts covered in ${title}.`,
    `Use scientific vocabulary accurately when discussing ${title}.`,
    `Apply the scientific method to questions related to ${title}.`,
    `Analyze data and observations connected to ${title}.`,
    `Connect ${title} concepts to real-world applications.`
  ];

  if (has(title, 'plant', 'photosynth', 'seed', 'flower')) {
    vocab = [
      { term: 'Photosynthesis', definition: 'The process by which plants convert sunlight, water, and carbon dioxide into glucose and oxygen.' },
      { term: 'Chlorophyll', definition: 'The green pigment in plant cells that absorbs light energy for photosynthesis.' },
      { term: 'Chloroplast', definition: 'The organelle in plant cells where photosynthesis takes place.' },
      { term: 'Germination', definition: 'The process by which a seed begins to grow into a new plant.' },
      { term: 'Pollination', definition: 'The transfer of pollen from the male part of a flower to the female part.' },
      { term: 'Root System', definition: 'The underground parts of a plant that absorb water and nutrients.' }
    ];
    content = `Plants are living organisms that produce their own food through photosynthesis. This process takes place in the chloroplasts of plant cells, using chlorophyll (the green pigment) to capture light energy.\n\nThe equation for photosynthesis is: 6CO₂ + 6H₂O + light energy → C₆H₁₂O₆ + 6O₂. In words: carbon dioxide plus water plus sunlight produces glucose (sugar) and oxygen. The glucose provides energy for the plant, and the oxygen is released into the air — which is what animals and humans breathe.\n\nPlants have a life cycle: seed → germination → seedling → mature plant → flower → pollination → seed production. Roots absorb water and minerals from the soil. Stems transport water and nutrients. Leaves are the primary site of photosynthesis.\n\nPlants are essential to life on Earth. They produce oxygen, provide food, prevent soil erosion, and form the base of most food chains.`;
    examples = [
      { title: 'Photosynthesis Equation', content: '6CO₂ + 6H₂O + sunlight → C₆H₁₂O₆ + 6O₂. Reactants: carbon dioxide and water. Products: glucose and oxygen. Energy source: sunlight.', solution: 'Plants take in CO₂ and water, use sunlight, and produce sugar and oxygen.' },
      { title: 'Plant Life Cycle', content: 'A bean seed is planted in soil → it absorbs water and germinates → a root grows down, a shoot grows up → leaves develop and photosynthesis begins → the plant flowers → bees pollinate the flowers → new bean pods (seeds) form.', solution: 'Seed → Germination → Growth → Flowering → Pollination → Seed Production' }
    ];
    practice = [
      { question: 'What three things does a plant need for photosynthesis?', hint: 'Think about what the plant takes in from its environment.', answer: 'Sunlight, water, and carbon dioxide.' },
      { question: 'Explain why plants appear green.', hint: 'Think about which pigment is involved in photosynthesis.', answer: 'Chlorophyll absorbs red and blue light and reflects green light.' }
    ];

  } else if (has(title, 'cell', 'organelle', 'mitosis', 'meiosis', 'membran')) {
    vocab = [
      { term: 'Cell', definition: 'The basic unit of life; the smallest structure that can perform all life functions.' },
      { term: 'Nucleus', definition: 'The organelle that contains the cell\'s DNA and controls cell activities.' },
      { term: 'Mitochondria', definition: 'Organelles that produce energy (ATP) through cellular respiration.' },
      { term: 'Cell Membrane', definition: 'The outer boundary of the cell that controls what enters and exits.' },
      { term: 'Cytoplasm', definition: 'The gel-like fluid inside the cell that holds organelles in place.' },
      { term: 'Ribosome', definition: 'Organelles that produce proteins by translating genetic instructions.' }
    ];
    content = `All living things are made of cells — the basic units of life. There are two main types: prokaryotic cells (no nucleus, like bacteria) and eukaryotic cells (with a nucleus, like plant and animal cells).\n\nEvery cell has essential components. The cell membrane controls what enters and leaves. The cytoplasm is the gel-like substance that fills the cell. The nucleus houses DNA, which contains genetic instructions. Mitochondria are the "powerhouses" that produce energy through cellular respiration.\n\nPlant cells have additional structures: a rigid cell wall for support, chloroplasts for photosynthesis, and a large central vacuole for storage.\n\nCells reproduce through cell division. Mitosis produces two identical cells for growth and repair. Meiosis produces four genetically unique cells for sexual reproduction.`;
    examples = [
      { title: 'Animal vs. Plant Cell', content: 'Both have: nucleus, mitochondria, cell membrane, ribosomes. Only plant cells have: cell wall, chloroplasts, large central vacuole.', solution: 'Plant cells have structures for photosynthesis and structural support that animal cells lack.' }
    ];
    practice = [
      { question: 'What is the function of the mitochondria?', hint: 'Think about energy production.', answer: 'Mitochondria produce ATP (energy) through cellular respiration.' },
      { question: 'Name two differences between plant and animal cells.', hint: 'Think about structures unique to plant cells.', answer: 'Plant cells have cell walls and chloroplasts; animal cells do not.' }
    ];

  } else if (has(title, 'weather', 'climate', 'atmosphere', 'cloud', 'water cycle', 'precipitation')) {
    vocab = [
      { term: 'Weather', definition: 'The short-term atmospheric conditions at a specific time and place.' },
      { term: 'Climate', definition: 'The average weather conditions in a region over a long period of time.' },
      { term: 'Evaporation', definition: 'The process by which liquid water becomes water vapor (gas).' },
      { term: 'Condensation', definition: 'The process by which water vapor cools and becomes liquid water (forms clouds).' },
      { term: 'Precipitation', definition: 'Water that falls from clouds as rain, snow, sleet, or hail.' },
      { term: 'Atmosphere', definition: 'The layer of gases surrounding Earth.' }
    ];
    content = `Weather describes the short-term conditions of the atmosphere — temperature, humidity, precipitation, wind, and cloud cover. Climate is the long-term pattern of weather in a region.\n\nThe water cycle is the continuous movement of water through Earth's systems. It has four main stages: evaporation (water becomes vapor), condensation (vapor forms clouds), precipitation (water falls as rain or snow), and collection (water gathers in bodies of water or soaks into ground). The Sun's energy drives the water cycle.\n\nDifferent types of clouds indicate different weather. Cumulus clouds are fluffy and often mean fair weather. Stratus clouds are flat layers that may bring steady rain. Cumulonimbus clouds are tall and bring thunderstorms.\n\nWeather is measured using instruments: thermometers (temperature), barometers (air pressure), anemometers (wind speed), and rain gauges (precipitation).`;
    examples = [
      { title: 'The Water Cycle', content: 'Sun heats a lake → water evaporates into vapor → vapor rises and cools → condensation forms clouds → clouds produce precipitation (rain) → rain flows back into the lake.', solution: 'Evaporation → Condensation → Precipitation → Collection' }
    ];
    practice = [
      { question: 'Explain the difference between weather and climate.', hint: 'One is short-term, the other is long-term.', answer: 'Weather is daily atmospheric conditions; climate is the average conditions over decades.' },
      { question: 'Describe what happens during condensation in the water cycle.', hint: 'What happens when water vapor cools?', answer: 'Water vapor cools and changes from gas to liquid, forming clouds.' }
    ];

  } else if (has(title, 'force', 'motion', 'newton', 'gravity', 'friction', 'accelerat', 'velocity', 'momentum')) {
    vocab = [
      { term: 'Force', definition: 'A push or pull that can change an object\'s motion.' },
      { term: 'Newton\'s First Law', definition: 'An object at rest stays at rest, and an object in motion stays in motion, unless acted on by an outside force (inertia).' },
      { term: 'Newton\'s Second Law', definition: 'Force equals mass times acceleration (F = ma).' },
      { term: 'Newton\'s Third Law', definition: 'For every action, there is an equal and opposite reaction.' },
      { term: 'Friction', definition: 'A force that opposes the motion of objects in contact.' },
      { term: 'Gravity', definition: 'The force of attraction between objects with mass; on Earth, g ≈ 9.8 m/s².' },
      { term: 'Acceleration', definition: 'The rate of change of velocity over time.' }
    ];
    content = `Force is a push or pull that can change an object's speed, direction, or shape. Newton's three laws of motion describe how forces affect objects.\n\nNewton's First Law (Inertia): An object at rest stays at rest, and an object in motion stays in motion at constant velocity, unless a net external force acts on it. A ball on a table won't move unless pushed.\n\nNewton's Second Law: Force = mass × acceleration (F = ma). A greater force produces greater acceleration. A more massive object needs more force to accelerate at the same rate.\n\nNewton's Third Law: Every action has an equal and opposite reaction. When you push against a wall, the wall pushes back on you with equal force.\n\nFriction is a force that opposes motion between surfaces in contact. Gravity is the force that pulls objects toward each other — on Earth, it accelerates objects downward at 9.8 m/s².`;
    examples = [
      { title: 'Newton\'s Second Law', content: 'A 10 kg box is pushed with a force of 50 N. What is its acceleration? F = ma → 50 = 10 × a → a = 50/10.', solution: 'a = 5 m/s²' },
      { title: 'Newton\'s Third Law', content: 'A swimmer pushes water backward (action). The water pushes the swimmer forward (reaction). This is why swimming works.', solution: 'Action and reaction forces are equal in magnitude and opposite in direction.' }
    ];
    practice = [
      { question: 'Calculate: A 5 kg object accelerates at 3 m/s². What force is acting on it?', hint: 'Use F = ma.', answer: 'F = 5 × 3 = 15 N' },
      { question: 'Explain why a soccer ball eventually stops rolling on grass.', hint: 'What force opposes the ball\'s motion?', answer: 'Friction between the ball and grass slows it down until it stops.' }
    ];

  } else if (has(title, 'chem', 'element', 'atom', 'molecule', 'react', 'compound', 'periodic', 'bond')) {
    vocab = [
      { term: 'Atom', definition: 'The smallest unit of an element that retains the properties of that element.' },
      { term: 'Element', definition: 'A pure substance made of only one type of atom.' },
      { term: 'Compound', definition: 'A substance made of two or more elements chemically bonded together.' },
      { term: 'Molecule', definition: 'Two or more atoms bonded together.' },
      { term: 'Chemical Reaction', definition: 'A process where substances (reactants) change into new substances (products).' },
      { term: 'Periodic Table', definition: 'An organized chart of all known elements arranged by atomic number.' }
    ];
    content = `Chemistry studies matter and how it changes. All matter is made of atoms — tiny particles composed of protons (positive), neutrons (neutral), and electrons (negative).\n\nElements are pure substances made of one type of atom. The periodic table organizes all known elements by atomic number. Elements in the same column (group) share similar properties. Metals are on the left, nonmetals on the right.\n\nAtoms bond together to form compounds and molecules. Ionic bonds form when atoms transfer electrons (metals + nonmetals). Covalent bonds form when atoms share electrons (nonmetals + nonmetals).\n\nIn a chemical reaction, reactants transform into products. The law of conservation of mass states that matter is neither created nor destroyed — the total mass of reactants equals the total mass of products. Chemical equations must be balanced to reflect this.`;
    examples = [
      { title: 'Balancing an Equation', content: 'Unbalanced: H₂ + O₂ → H₂O. Count atoms: 2H and 2O on left, 2H and 1O on right. Balanced: 2H₂ + O₂ → 2H₂O.', solution: '2H₂ + O₂ → 2H₂O (4H and 2O on each side)' }
    ];
    practice = [
      { question: 'What is the difference between an element and a compound?', hint: 'Think about how many types of atoms are involved.', answer: 'An element is one type of atom; a compound is two or more elements bonded together.' },
      { question: 'Is NaCl (table salt) an ionic or covalent compound?', hint: 'Na is a metal, Cl is a nonmetal.', answer: 'Ionic — metals and nonmetals form ionic bonds by transferring electrons.' }
    ];

  } else if (has(title, 'earth', 'rock', 'mineral', 'plate', 'tectonic', 'volcano', 'earthquake', 'erosion', 'geolog')) {
    vocab = [
      { term: 'Igneous Rock', definition: 'Rock formed from cooled and solidified magma or lava.' },
      { term: 'Sedimentary Rock', definition: 'Rock formed from compressed layers of sediment over time.' },
      { term: 'Metamorphic Rock', definition: 'Rock that has been changed by heat and pressure.' },
      { term: 'Plate Tectonics', definition: 'The theory that Earth\'s crust is divided into plates that move on the mantle.' },
      { term: 'Erosion', definition: 'The wearing away and transport of rock and soil by wind, water, or ice.' },
      { term: 'Weathering', definition: 'The breaking down of rocks by physical, chemical, or biological processes.' }
    ];
    content = `Earth's structure consists of layers: the crust (thin outer layer), mantle (thick layer of semi-solid rock), outer core (liquid metal), and inner core (solid metal).\n\nThe theory of plate tectonics explains that Earth's crust is divided into large plates that float on the semi-liquid mantle. Where plates meet, we see earthquakes, volcanoes, and mountain formation. Convergent boundaries (plates colliding) create mountains. Divergent boundaries (plates separating) create rift valleys. Transform boundaries (plates sliding past each other) cause earthquakes.\n\nThe rock cycle describes how rocks continuously change form. Igneous rocks form when magma cools. Sedimentary rocks form when layers of sediment are compressed over time. Metamorphic rocks form when existing rocks are changed by heat and pressure. Any rock type can transform into any other over geological time.\n\nWeathering breaks rocks down. Erosion moves the broken material. Deposition drops it in new locations. These processes shape Earth's surface over millions of years.`;
    examples = [
      { title: 'The Rock Cycle', content: 'Granite (igneous) → weathering breaks it into sediment → sediment compresses into sandstone (sedimentary) → heat and pressure transform it into quartzite (metamorphic) → melting creates magma → cooling forms new igneous rock.', solution: 'Rocks cycle between igneous, sedimentary, and metamorphic forms.' }
    ];
    practice = [
      { question: 'Name the three types of rocks and how each is formed.', hint: 'Think about cooling, compression, and transformation.', answer: 'Igneous (cooled magma), Sedimentary (compressed sediment), Metamorphic (changed by heat/pressure).' },
      { question: 'What happens at a convergent plate boundary?', hint: 'What occurs when two plates push together?', answer: 'Plates collide, forming mountains or subduction zones (one plate slides under another).' }
    ];

  } else if (has(title, 'space', 'planet', 'solar', 'star', 'moon', 'orbit', 'galaxy', 'universe', 'astro')) {
    vocab = [
      { term: 'Solar System', definition: 'The Sun and all objects that orbit around it, including planets, moons, asteroids, and comets.' },
      { term: 'Orbit', definition: 'The curved path an object follows as it revolves around another object due to gravity.' },
      { term: 'Rotation', definition: 'The spinning of an object on its axis (causes day and night on Earth).' },
      { term: 'Revolution', definition: 'The movement of an object around another object (Earth revolves around the Sun, creating a year).' },
      { term: 'Light-Year', definition: 'The distance light travels in one year — about 5.88 trillion miles.' },
      { term: 'Galaxy', definition: 'A massive system of stars, gas, and dust held together by gravity.' }
    ];
    content = `Our solar system consists of the Sun, eight planets, their moons, and many smaller objects. The four inner planets (Mercury, Venus, Earth, Mars) are rocky. The four outer planets (Jupiter, Saturn, Uranus, Neptune) are gas or ice giants.\n\nEarth rotates on its axis once every 24 hours, creating day and night. It revolves around the Sun once every 365.25 days, creating a year. The tilt of Earth's axis (23.5°) causes the seasons as different parts of Earth receive varying amounts of sunlight throughout the year.\n\nStars are massive balls of hot gas that produce energy through nuclear fusion. Our Sun is a medium-sized star. Stars vary in size, temperature, color, and brightness. They go through a life cycle: nebula → main sequence star → red giant → white dwarf (or supernova for massive stars).\n\nOur galaxy, the Milky Way, contains billions of stars. The observable universe contains billions of galaxies.`;
    examples = [
      { title: 'Why Seasons Occur', content: 'In June, the Northern Hemisphere tilts toward the Sun → longer days, more direct sunlight → summer. In December, it tilts away → shorter days, less direct sunlight → winter. The Southern Hemisphere has opposite seasons.', solution: 'Seasons are caused by Earth\'s axial tilt, not distance from the Sun.' }
    ];
    practice = [
      { question: 'List the eight planets in order from the Sun.', hint: 'My Very Educated Mother Just Served Us Nachos.', answer: 'Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune' },
      { question: 'What is the difference between rotation and revolution?', hint: 'One is spinning, the other is orbiting.', answer: 'Rotation is spinning on an axis (day/night). Revolution is orbiting around another object (year).' }
    ];

  } else if (has(title, 'ecosystem', 'biome', 'food chain', 'habitat', 'environment', 'ecolog', 'biodiv')) {
    vocab = [
      { term: 'Ecosystem', definition: 'A community of living organisms interacting with their physical environment.' },
      { term: 'Food Chain', definition: 'A sequence showing how energy and nutrients pass from one organism to another.' },
      { term: 'Producer', definition: 'An organism that makes its own food (usually through photosynthesis).' },
      { term: 'Consumer', definition: 'An organism that eats other organisms for energy.' },
      { term: 'Decomposer', definition: 'An organism that breaks down dead material and recycles nutrients.' },
      { term: 'Biome', definition: 'A large region characterized by its climate and the types of organisms that live there.' }
    ];
    content = `An ecosystem includes all living things (biotic factors) and nonliving things (abiotic factors) in an area, and the interactions between them. Biotic factors include plants, animals, and microorganisms. Abiotic factors include sunlight, water, temperature, and soil.\n\nEnergy flows through ecosystems in food chains and food webs. Producers (plants) capture energy from the Sun. Primary consumers (herbivores) eat producers. Secondary consumers (carnivores) eat primary consumers. Decomposers break down dead organisms and recycle nutrients back into the soil.\n\nOnly about 10% of energy transfers from one level to the next. This is why there are fewer top predators than herbivores in any ecosystem.\n\nBiomes are large-scale ecosystems defined by climate. Major biomes include tropical rainforest, desert, grassland, temperate forest, taiga (boreal forest), and tundra. Each biome supports different types of organisms adapted to its conditions.`;
    examples = [
      { title: 'Food Chain Example', content: 'Grass (producer) → Grasshopper (primary consumer) → Frog (secondary consumer) → Snake (tertiary consumer) → Hawk (top predator). Decomposers recycle nutrients from dead organisms at every level.', solution: 'Energy flows from producers to consumers, with only ~10% transferred at each step.' }
    ];
    practice = [
      { question: 'Create a food chain with at least four organisms. Label each as producer, primary consumer, secondary consumer, or top predator.', hint: 'Start with a plant (producer) and build up.', answer: null },
      { question: 'What would happen to an ecosystem if all decomposers disappeared?', hint: 'Think about what decomposers do with dead material and nutrients.', answer: 'Dead material would pile up and nutrients would not be recycled back into the soil, eventually starving producers.' }
    ];

  } else if (has(title, 'energy', 'electric', 'magnet', 'circuit', 'wave', 'sound', 'light')) {
    vocab = [
      { term: 'Energy', definition: 'The ability to do work or cause change.' },
      { term: 'Kinetic Energy', definition: 'The energy of motion (KE = ½mv²).' },
      { term: 'Potential Energy', definition: 'Stored energy based on position or condition.' },
      { term: 'Circuit', definition: 'A closed loop through which electric current can flow.' },
      { term: 'Wavelength', definition: 'The distance between two consecutive peaks of a wave.' },
      { term: 'Frequency', definition: 'The number of wave cycles that pass a point per second, measured in Hertz (Hz).' }
    ];
    content = `Energy is the ability to do work or cause change. It comes in many forms: kinetic (motion), potential (stored), thermal (heat), electrical, chemical, nuclear, light, and sound.\n\nThe law of conservation of energy states that energy cannot be created or destroyed — only transformed from one form to another. A roller coaster at the top of a hill has potential energy. As it descends, potential energy converts to kinetic energy.\n\nElectrical circuits require a power source, a conductor, and a load (like a light bulb). Current flows through a closed circuit. A switch opens or closes the circuit. Series circuits have one path; parallel circuits have multiple paths.\n\nWaves transfer energy without transferring matter. Mechanical waves (sound) need a medium. Electromagnetic waves (light) can travel through empty space. All waves have wavelength, frequency, and amplitude.`;
    examples = [
      { title: 'Energy Transformation', content: 'A flashlight: Chemical energy (battery) → Electrical energy (circuit) → Light energy (bulb) + Thermal energy (heat).', solution: 'Energy transforms between forms but the total amount stays the same.' }
    ];
    practice = [
      { question: 'List three energy transformations that happen when you ride a bicycle.', hint: 'Chemical energy in your body starts the chain.', answer: 'Chemical → kinetic (pedaling) → mechanical (wheels turning) → some thermal (friction/heat).' },
      { question: 'What is the difference between a series circuit and a parallel circuit?', hint: 'Think about the path electricity follows.', answer: 'Series has one path (if one component fails, all fail). Parallel has multiple paths (components work independently).' }
    ];

  } else if (has(title, 'genet', 'dna', 'hered', 'gene', 'trait', 'chromosome', 'evolut', 'natural select', 'adapt')) {
    vocab = [
      { term: 'DNA', definition: 'Deoxyribonucleic acid; the molecule that carries genetic instructions.' },
      { term: 'Gene', definition: 'A segment of DNA that codes for a specific protein or trait.' },
      { term: 'Chromosome', definition: 'A structure made of DNA and proteins; humans have 46 (23 pairs).' },
      { term: 'Dominant Trait', definition: 'A trait that is expressed when at least one dominant allele is present.' },
      { term: 'Recessive Trait', definition: 'A trait that is only expressed when two recessive alleles are present.' },
      { term: 'Natural Selection', definition: 'The process by which organisms with favorable traits are more likely to survive and reproduce.' }
    ];
    content = `Genetics is the study of heredity — how traits are passed from parents to offspring. DNA (deoxyribonucleic acid) is the molecule that stores genetic information in the form of a double helix.\n\nGenes are segments of DNA that code for specific traits (like eye color or blood type). Humans have about 20,000–25,000 genes organized on 23 pairs of chromosomes. One chromosome in each pair comes from each parent.\n\nTraits can be dominant or recessive. A dominant allele (represented by a capital letter, like B) is expressed when present. A recessive allele (lowercase, like b) is only expressed when two copies are present (bb). A Punnett square helps predict the probability of offspring inheriting specific traits.\n\nEvolution through natural selection explains how populations change over time. Organisms with traits better suited to their environment are more likely to survive and reproduce, passing those traits to the next generation.`;
    examples = [
      { title: 'Punnett Square', content: 'Cross Bb × Bb (both parents carry one dominant and one recessive allele). Results: BB (25%), Bb (50%), bb (25%). So 75% show the dominant trait and 25% show the recessive trait.', solution: '3:1 ratio of dominant to recessive phenotypes.' }
    ];
    practice = [
      { question: 'If both parents have the genotype Bb for eye color (B = brown, b = blue), what percentage of offspring could have blue eyes?', hint: 'Set up a Punnett square with Bb × Bb.', answer: '25% (bb)' },
      { question: 'Explain how natural selection leads to adaptation over time.', hint: 'Think about which individuals survive and reproduce more successfully.', answer: 'Organisms with favorable traits survive and reproduce more, passing those traits to offspring. Over generations, the population becomes better adapted.' }
    ];

  } else {
    vocab = [
      { term: 'Hypothesis', definition: 'A testable prediction based on observation and prior knowledge.' },
      { term: 'Variable', definition: 'A factor that can change in an experiment.' },
      { term: 'Control Group', definition: 'The group in an experiment that does not receive the treatment, used for comparison.' },
      { term: 'Data', definition: 'Information collected through observation and measurement.' },
      { term: 'Conclusion', definition: 'A summary of findings based on data analysis.' }
    ];
    content = `This lesson covers scientific concepts related to ${title}. Science is the systematic study of the natural world through observation, experimentation, and analysis.\n\nThe scientific method provides a framework for investigation: observe → ask a question → research → form a hypothesis → design and conduct an experiment → analyze data → draw conclusions → communicate results.\n\nWhen designing an experiment, identify the independent variable (what you change), the dependent variable (what you measure), and the controlled variables (what you keep the same). A control group provides a baseline for comparison.\n\nAlways record observations carefully and accurately. Look for patterns in your data. Your conclusion should state whether the data supports or does not support your hypothesis.`;
    examples = [
      { title: 'Scientific Method in Action', content: `Observation: Plants near the window grow taller. Question: Does more sunlight help plants grow? Hypothesis: Plants exposed to more sunlight will grow taller. Experiment: Grow identical plants with different amounts of light. Measure height after 2 weeks.`, solution: 'The scientific method turns observations into testable experiments.' }
    ];
    practice = [
      { question: `Design a simple experiment related to ${title}. Identify the independent and dependent variables.`, hint: 'What would you change? What would you measure?', answer: null }
    ];
  }

  return { objectives, content, vocabulary: vocab, examples, practice };
}

// ================================================================
// SOCIAL STUDIES CONTENT
// ================================================================
function ssContent(title, grade, unitTitle) {
  let objectives, content, vocab, examples, practice;

  objectives = [
    `Explain the key ideas and events related to ${title}.`,
    `Use historical vocabulary when discussing ${title}.`,
    `Analyze causes and effects connected to ${title}.`,
    `Connect past events to present-day situations.`,
    `Evaluate different perspectives on ${title}.`
  ];

  if (has(title, 'government', 'constitution', 'branch', 'democra', 'rights', 'civic', 'law', 'citizen')) {
    vocab = [
      { term: 'Constitution', definition: 'The supreme law of the land; establishes the structure and powers of government.' },
      { term: 'Democracy', definition: 'A system of government where citizens have the power to choose their leaders.' },
      { term: 'Legislative Branch', definition: 'The branch of government that makes laws (Congress: Senate + House of Representatives).' },
      { term: 'Executive Branch', definition: 'The branch of government that enforces laws (President and Cabinet).' },
      { term: 'Judicial Branch', definition: 'The branch of government that interprets laws (Supreme Court and federal courts).' },
      { term: 'Bill of Rights', definition: 'The first ten amendments to the U.S. Constitution, guaranteeing individual freedoms.' }
    ];
    content = `The United States is a constitutional republic — a form of democracy where citizens elect representatives to make laws, guided by the Constitution.\n\nThe Constitution divides government into three branches to prevent any one group from having too much power (separation of powers). The legislative branch (Congress) writes laws. The executive branch (President) enforces laws. The judicial branch (courts) interprets laws. Each branch can limit the others through checks and balances.\n\nThe Bill of Rights protects individual freedoms: freedom of speech, religion, press, assembly, and petition (1st Amendment); the right to bear arms (2nd); protection from unreasonable searches (4th); the right to a fair trial (6th); and protection against cruel punishment (8th).\n\nCitizens participate in democracy by voting, serving on juries, paying taxes, staying informed, and engaging in civic life.`;
    examples = [
      { title: 'Checks and Balances', content: 'Congress passes a law → President can veto it → Congress can override with 2/3 vote → Supreme Court can declare it unconstitutional. Each branch checks the others.', solution: 'No single branch can act without oversight from the others.' }
    ];
    practice = [
      { question: 'Name the three branches of government and the main function of each.', hint: 'Think: make laws, enforce laws, interpret laws.', answer: 'Legislative (makes laws), Executive (enforces laws), Judicial (interprets laws).' },
      { question: 'Why is the system of checks and balances important?', hint: 'What would happen if one branch had unlimited power?', answer: 'It prevents any one branch from becoming too powerful, protecting citizens\' rights.' }
    ];

  } else if (has(title, 'revolution', 'independence', 'colonial', 'found', 'war', 'civil', 'world war', 'conflict')) {
    vocab = [
      { term: 'Revolution', definition: 'A fundamental change in political power or organizational structures, often achieved through force.' },
      { term: 'Independence', definition: 'Freedom from the control or authority of another nation.' },
      { term: 'Patriot', definition: 'A colonist who supported independence from Britain.' },
      { term: 'Treaty', definition: 'A formal agreement between nations.' },
      { term: 'Cause', definition: 'An event or condition that leads to a result.' },
      { term: 'Effect', definition: 'The result or outcome of a cause.' }
    ];
    content = `Throughout history, conflicts and revolutions have shaped nations and reshaped the world. Understanding these events requires examining their causes, key events, and lasting effects.\n\nEvery major conflict has multiple causes — political, economic, social, and ideological. The American Revolution, for example, was caused by taxation without representation, restrictions on colonial trade, and the desire for self-governance.\n\nWars and conflicts produce both immediate and long-term effects. They change borders, create new governments, affect economies, and alter societies. The aftermath often includes treaties, new laws, and shifts in political power.\n\nWhen studying conflicts, consider multiple perspectives. Different groups may experience the same event very differently. Examining primary sources — letters, documents, speeches from the time — helps us understand these perspectives.`;
    examples = [
      { title: 'Cause and Effect', content: 'Cause: British Parliament imposed the Stamp Act (1765), taxing printed materials in the colonies. Effect: Colonists protested ("No taxation without representation"), eventually leading to the American Revolution.', solution: 'Historical events have interconnected causes and effects.' }
    ];
    practice = [
      { question: `Identify two causes and two effects of a major conflict related to ${title}.`, hint: 'Think about what led to the event and what changed because of it.', answer: null },
      { question: 'Why is it important to examine multiple perspectives when studying historical conflicts?', hint: 'Different groups may have experienced events differently.', answer: 'Different groups had different motivations, experiences, and outcomes. Understanding multiple perspectives gives a more complete picture.' }
    ];

  } else if (has(title, 'geography', 'map', 'region', 'continent', 'ocean', 'landform')) {
    vocab = [
      { term: 'Continent', definition: 'One of the seven large landmasses on Earth.' },
      { term: 'Latitude', definition: 'Lines that run east-west and measure distance north or south of the Equator.' },
      { term: 'Longitude', definition: 'Lines that run north-south and measure distance east or west of the Prime Meridian.' },
      { term: 'Landform', definition: 'A natural feature of Earth\'s surface (mountains, valleys, plains, plateaus).' },
      { term: 'Climate Zone', definition: 'A region with consistent weather patterns (tropical, temperate, polar).' },
      { term: 'Natural Resource', definition: 'Materials from nature that people use (water, minerals, timber, soil).' }
    ];
    content = `Geography studies Earth's physical features, climates, and human populations. Physical geography examines landforms, water systems, and climate. Human geography examines where and how people live.\n\nMaps are essential tools. Political maps show borders and cities. Physical maps show landforms and elevation. Thematic maps display specific data (population, climate, resources). Maps use a compass rose for direction, a scale for distance, and a legend (key) to explain symbols.\n\nEarth has seven continents (Africa, Antarctica, Asia, Australia, Europe, North America, South America) and five oceans (Pacific, Atlantic, Indian, Southern, Arctic). Latitude and longitude create a coordinate system for locating any place on Earth.\n\nGeography influences human settlement, culture, and economic activity. People settle near water sources, fertile land, and moderate climates. Natural resources shape economies — oil-rich regions develop differently than agricultural regions.`;
    examples = [
      { title: 'Reading Coordinates', content: 'Washington, D.C. is located at approximately 38°N latitude, 77°W longitude. The "N" means north of the Equator, and "W" means west of the Prime Meridian.', solution: 'Latitude and longitude pinpoint any location on Earth.' }
    ];
    practice = [
      { question: 'Name the seven continents and the three largest oceans.', hint: 'Use the first letter of each continent as a memory aid.', answer: 'Continents: Africa, Antarctica, Asia, Australia, Europe, North America, South America. Oceans: Pacific, Atlantic, Indian.' },
      { question: 'Explain how geography influences where people choose to live.', hint: 'Think about water, climate, and resources.', answer: 'People settle near water, fertile soil, and moderate climates where they can grow food, access resources, and travel.' }
    ];

  } else if (has(title, 'econom', 'trade', 'market', 'supply', 'demand', 'financ', 'money', 'budget')) {
    vocab = [
      { term: 'Supply', definition: 'The amount of a product or service available for sale.' },
      { term: 'Demand', definition: 'The desire and ability of consumers to buy a product or service.' },
      { term: 'Scarcity', definition: 'The condition of having limited resources to meet unlimited wants.' },
      { term: 'Opportunity Cost', definition: 'What you give up when you choose one option over another.' },
      { term: 'GDP', definition: 'Gross Domestic Product; the total value of goods and services produced in a country in a year.' },
      { term: 'Inflation', definition: 'A general increase in prices over time, reducing purchasing power.' }
    ];
    content = `Economics studies how people, businesses, and governments make decisions about using limited resources. The fundamental problem of economics is scarcity: there are unlimited wants but limited resources.\n\nSupply and demand determine prices in a market economy. When demand increases and supply stays the same, prices rise. When supply increases and demand stays the same, prices fall. The equilibrium price is where supply and demand meet.\n\nOpportunity cost is what you give up when making a choice. If you spend $20 on a book, the opportunity cost is whatever else you could have bought with that $20.\n\nGovernments influence economies through taxation, spending, and regulation. Fiscal policy involves government spending and taxation. Monetary policy involves managing the money supply and interest rates.`;
    examples = [
      { title: 'Supply and Demand', content: 'A popular toy at holiday time: demand is high but supply is limited → price increases. After the holidays: demand drops → price decreases or stores offer sales.', solution: 'Prices rise when demand exceeds supply and fall when supply exceeds demand.' }
    ];
    practice = [
      { question: 'You have $50. You can buy a video game or go to a concert. If you choose the game, what is the opportunity cost?', hint: 'Opportunity cost is what you give up.', answer: 'The concert experience is the opportunity cost.' },
      { question: 'Explain what happens to the price of umbrellas when it starts raining heavily.', hint: 'How does rain affect demand for umbrellas?', answer: 'Demand increases while supply stays the same, so the price tends to rise.' }
    ];

  } else {
    vocab = [
      { term: 'Primary Source', definition: 'An original document or object from the time period being studied.' },
      { term: 'Secondary Source', definition: 'A source that analyzes or interprets primary sources (textbooks, articles).' },
      { term: 'Chronology', definition: 'The arrangement of events in the order they occurred.' },
      { term: 'Perspective', definition: 'A particular point of view or way of looking at events.' },
      { term: 'Bias', definition: 'A tendency to favor one side, sometimes unfairly; present in many historical sources.' }
    ];
    content = `This lesson explores important concepts related to ${title}. Social studies encompasses history, geography, government, economics, and culture.\n\nWhen studying ${title}, consider the historical context — what was happening in the world at that time? Who were the key people and groups involved? What were their motivations?\n\nCritical analysis of sources is essential. Primary sources (diaries, speeches, photographs) give us direct evidence from the time period. Secondary sources (textbooks, documentaries) provide analysis and interpretation. Consider the author's perspective and possible bias when evaluating any source.\n\nConnecting past events to the present helps us understand why the world is the way it is today. Many current institutions, borders, and social systems have roots in historical events.`;
    examples = [
      { title: 'Analyzing a Source', content: `When studying ${title}, ask: Who created this source? When? Why? What perspective does it represent? What might be missing?`, solution: 'Critical analysis reveals more than surface-level reading.' }
    ];
    practice = [
      { question: `Identify one key event, person, or concept related to ${title} and explain its significance.`, hint: 'Choose something that had a lasting impact.', answer: null },
      { question: `How does ${title} connect to or affect the present day?`, hint: 'Think about lasting impacts on laws, culture, or geography.', answer: null }
    ];
  }

  return { objectives, content, vocabulary: vocab, examples, practice };
}

// ================================================================
// ELECTIVE CONTENT (Music, Art, Spanish, French, PE, Tech, Health)
// ================================================================
function electiveContent(subject, title, grade, unitTitle) {
  let objectives = [
    `Understand the key concepts presented in ${title}.`,
    `Apply skills and knowledge from ${title} in practical exercises.`,
    `Use appropriate vocabulary related to ${title}.`,
    `Demonstrate progress in ${subject} through ${title} activities.`,
    `Reflect on your learning and identify areas for growth.`
  ];

  let content, vocab, examples, practice;

  if (subject === 'Music') {
    vocab = [
      { term: 'Rhythm', definition: 'The pattern of beats and silences in music.' },
      { term: 'Melody', definition: 'A sequence of musical notes that form a recognizable tune.' },
      { term: 'Harmony', definition: 'Two or more notes played together to create chords.' },
      { term: 'Tempo', definition: 'The speed at which music is performed.' },
      { term: 'Dynamics', definition: 'The volume of music (loud = forte, soft = piano).' },
      { term: 'Time Signature', definition: 'Indicates how many beats are in each measure and which note gets one beat.' }
    ];
    content = `Music is organized sound. The building blocks of music include rhythm (patterns of beats), melody (a sequence of pitches), harmony (multiple notes played together), and form (the structure of a piece).\n\nReading music requires understanding staff notation. The treble clef (G clef) is used for higher-pitched instruments and voices. The bass clef (F clef) is used for lower-pitched instruments. Notes on the lines of the treble clef are E, G, B, D, F ("Every Good Boy Does Fine"). Notes in the spaces spell F-A-C-E.\n\nRhythm is organized by time signatures. In 4/4 time, there are four beats per measure and a quarter note gets one beat. A whole note lasts 4 beats, a half note lasts 2, and an eighth note lasts half a beat.\n\nDynamics describe volume: pianissimo (pp) = very soft, piano (p) = soft, mezzo forte (mf) = medium, forte (f) = loud, fortissimo (ff) = very loud.`;
  } else if (subject === 'Art') {
    vocab = [
      { term: 'Line', definition: 'A mark made on a surface; can be straight, curved, thick, thin, etc.' },
      { term: 'Shape', definition: 'A two-dimensional area defined by an outline (circle, square, triangle, etc.).' },
      { term: 'Form', definition: 'A three-dimensional shape with height, width, and depth.' },
      { term: 'Color Theory', definition: 'The study of how colors interact, including primary, secondary, and complementary colors.' },
      { term: 'Composition', definition: 'The arrangement of elements within an artwork.' },
      { term: 'Perspective', definition: 'A technique for creating the illusion of depth on a flat surface.' }
    ];
    content = `Art is the expression of ideas and emotions through visual media. The elements of art — line, shape, form, color, value, texture, and space — are the building blocks of any artwork.\n\nColor theory helps artists choose effective color combinations. The primary colors (red, blue, yellow) cannot be mixed from other colors. Secondary colors (orange, green, purple) are made by mixing two primaries. Complementary colors (opposite on the color wheel) create strong contrast.\n\nComposition refers to how elements are arranged. The rule of thirds suggests placing key elements along imaginary lines that divide the canvas into a 3×3 grid. Balance, contrast, emphasis, and unity are principles that guide effective composition.\n\nPerspective creates the illusion of depth. In one-point perspective, parallel lines converge at a single vanishing point on the horizon.`;
  } else if (subject === 'Spanish') {
    vocab = [
      { term: 'Sustantivo', definition: 'Noun — a word for a person, place, thing, or idea.' },
      { term: 'Verbo', definition: 'Verb — an action word.' },
      { term: 'Adjetivo', definition: 'Adjective — a word that describes a noun.' },
      { term: 'Conjugación', definition: 'Conjugation — changing a verb to match the subject.' },
      { term: 'Género', definition: 'Gender — in Spanish, nouns are masculine (el) or feminine (la).' },
      { term: 'Plural', definition: 'More than one — add -s or -es to make nouns plural in Spanish.' }
    ];
    content = `Spanish is the second most spoken native language in the world. Learning Spanish opens doors to communication with hundreds of millions of people across more than 20 countries.\n\nSpanish nouns have gender — they are either masculine or feminine. Most nouns ending in -o are masculine (el libro = the book) and most ending in -a are feminine (la mesa = the table). Articles (el, la, los, las) must match the noun's gender and number.\n\nVerb conjugation in Spanish changes based on the subject. Regular -ar verbs (like hablar = to speak): yo hablo, tú hablas, él/ella habla, nosotros hablamos, ellos/ellas hablan.\n\nBasic greetings: Hola (Hello), Buenos días (Good morning), Buenas tardes (Good afternoon), Buenas noches (Good evening), ¿Cómo estás? (How are you?), Bien, gracias (Fine, thanks).`;
  } else if (subject === 'French') {
    vocab = [
      { term: 'Nom', definition: 'Noun — a word for a person, place, thing, or idea.' },
      { term: 'Verbe', definition: 'Verb — an action word.' },
      { term: 'Adjectif', definition: 'Adjective — a word that describes a noun (usually placed after the noun in French).' },
      { term: 'Conjugaison', definition: 'Conjugation — changing a verb form to match the subject.' },
      { term: 'Genre', definition: 'Gender — French nouns are masculine (le) or feminine (la).' },
      { term: 'Article', definition: 'Le (masculine), La (feminine), Les (plural) — words placed before nouns.' }
    ];
    content = `French is spoken in over 29 countries across five continents. It is an official language of many international organizations.\n\nFrench nouns have gender — masculine (le, un) or feminine (la, une). There is no simple rule for all nouns, so gender should be memorized with each new vocabulary word.\n\nRegular -er verbs (like parler = to speak) are conjugated: je parle, tu parles, il/elle parle, nous parlons, vous parlez, ils/elles parlent.\n\nBasic expressions: Bonjour (Hello/Good day), Bonsoir (Good evening), Merci (Thank you), S'il vous plaît (Please), Comment allez-vous? (How are you? — formal), Je m'appelle... (My name is...).`;
  } else if (subject === 'PE' || subject === 'Physical Education') {
    vocab = [
      { term: 'Cardiovascular Endurance', definition: 'The ability of the heart and lungs to deliver oxygen during sustained activity.' },
      { term: 'Muscular Strength', definition: 'The maximum force a muscle can produce in a single effort.' },
      { term: 'Flexibility', definition: 'The range of motion around a joint.' },
      { term: 'Warm-Up', definition: 'Light activity to prepare the body for exercise and prevent injury.' },
      { term: 'Cool-Down', definition: 'Light activity after exercise to help the body recover.' }
    ];
    content = `Physical education develops fitness, coordination, and health knowledge. The five components of health-related fitness are cardiovascular endurance, muscular strength, muscular endurance, flexibility, and body composition.\n\nEvery workout should include a warm-up (5-10 minutes of light activity to increase heart rate and warm muscles), the main activity (20-40 minutes), and a cool-down (5-10 minutes of stretching and light movement).\n\nThe recommended daily physical activity for young people is 60 minutes of moderate to vigorous activity. This can include structured exercise, sports, active play, or activities like walking and cycling.\n\nGood sportsmanship means playing fairly, respecting opponents and officials, winning graciously, and losing with dignity.`;
  } else if (subject === 'Technology' || subject === 'Computer Science') {
    vocab = [
      { term: 'Algorithm', definition: 'A step-by-step set of instructions to solve a problem or complete a task.' },
      { term: 'Hardware', definition: 'The physical components of a computer system.' },
      { term: 'Software', definition: 'Programs and applications that run on hardware.' },
      { term: 'Digital Citizenship', definition: 'The responsible and ethical use of technology and the internet.' },
      { term: 'Cybersecurity', definition: 'The practice of protecting systems, networks, and data from digital attacks.' }
    ];
    content = `Technology literacy means understanding how to use digital tools effectively and responsibly. Computers consist of hardware (physical parts: CPU, RAM, storage, input/output devices) and software (programs: operating system, applications).\n\nAn algorithm is a step-by-step procedure for solving a problem. Algorithms are the foundation of computer programming. Before writing code, programmers plan their algorithms using pseudocode or flowcharts.\n\nDigital citizenship involves using technology responsibly: protecting personal information, respecting others online, recognizing credible sources, and understanding copyright.\n\nCybersecurity protects against threats. Best practices include using strong passwords, enabling two-factor authentication, keeping software updated, and being cautious with links and attachments.`;
  } else if (subject === 'Health') {
    vocab = [
      { term: 'Nutrition', definition: 'The process of obtaining food necessary for health and growth.' },
      { term: 'Nutrient', definition: 'A substance that provides nourishment: carbohydrates, proteins, fats, vitamins, minerals, water.' },
      { term: 'Mental Health', definition: 'Emotional, psychological, and social well-being.' },
      { term: 'Hygiene', definition: 'Practices that promote cleanliness and prevent disease.' },
      { term: 'Stress Management', definition: 'Techniques for coping with and reducing stress.' }
    ];
    content = `Health encompasses physical, mental, and social well-being. Good health habits established during youth create a foundation for lifelong wellness.\n\nNutrition fuels your body. A balanced diet includes fruits, vegetables, whole grains, lean proteins, and healthy fats. Limit added sugars, sodium, and processed foods. Staying hydrated by drinking water throughout the day supports every body function.\n\nMental health is equally important. Strategies for maintaining mental well-being include regular physical activity, adequate sleep (8-10 hours for teens), maintaining social connections, managing stress through healthy coping strategies, and seeking help when needed.\n\nPersonal hygiene — regular hand washing, dental care, bathing, and clean clothing — prevents the spread of illness and supports overall health.`;
  } else {
    vocab = [
      { term: 'Skill', definition: 'An ability acquired through practice and learning.' },
      { term: 'Practice', definition: 'Repeated exercise to improve a skill.' },
      { term: 'Application', definition: 'Using what you have learned in practical situations.' }
    ];
    content = `This lesson covers key concepts in ${subject} related to ${title}. Learning new skills requires understanding the fundamentals, practicing regularly, and applying what you learn.\n\nStart by understanding the core concepts. Read through the material carefully, take notes on key points, and ask questions about anything unclear.\n\nPractice is essential for building competence. Break complex skills into smaller steps and master each one before combining them. Regular practice, even in short sessions, is more effective than occasional long sessions.\n\nReflect on your progress. What have you learned? What do you still need to work on? Setting specific goals helps guide your learning.`;
  }

  examples = examples || [
    { title: `Applying ${subject} Skills`, content: `This example demonstrates a practical application of concepts from ${title}. Review the methods discussed in the lesson and apply them to this scenario.`, solution: 'Apply the steps and techniques from the lesson systematically.' }
  ];
  practice = practice || [
    { question: `Apply what you learned in ${title} to a practical exercise of your choice.`, hint: 'Use the vocabulary and techniques from this lesson.', answer: null },
    { question: `Reflect: What was the most important concept you learned in ${title}? How could you use it?`, hint: 'Think about real-world applications.', answer: null }
  ];

  return { objectives, content, vocabulary: vocab, examples, practice };
}

// ================================================================
// MAIN ROUTER
// ================================================================
function generateLessonContent(lesson) {
  const { title, subject, grade_level, unit_title } = lesson;
  const grade = parseInt(grade_level);

  if (['Math', 'Mathematics'].includes(subject)) return mathContent(title, grade, unit_title);
  if (['Language Arts', 'English', 'ELA'].includes(subject)) return elaContent(title, grade, unit_title);
  if (subject === 'Science') return scienceContent(title, grade, unit_title);
  if (['Social Studies', 'History', 'Government', 'Economics'].includes(subject)) return ssContent(title, grade, unit_title);
  return electiveContent(subject, title, grade, unit_title);
}

// ================================================================
// MAIN EXECUTION
// ================================================================
async function main() {
  console.log('============================================');
  console.log('JNM Home Education Program');
  console.log('Lesson Content Seed Script');
  console.log('============================================\n');

  try {
    // Step 1: Add columns (safe — IF NOT EXISTS)
    console.log('Step 1: Adding content columns to lessons table...');
    await pool.query('ALTER TABLE lessons ADD COLUMN IF NOT EXISTS learning_objectives TEXT');
    await pool.query('ALTER TABLE lessons ADD COLUMN IF NOT EXISTS instructional_content TEXT');
    await pool.query('ALTER TABLE lessons ADD COLUMN IF NOT EXISTS vocabulary JSONB');
    await pool.query('ALTER TABLE lessons ADD COLUMN IF NOT EXISTS examples JSONB');
    await pool.query('ALTER TABLE lessons ADD COLUMN IF NOT EXISTS guided_practice JSONB');
    await pool.query('ALTER TABLE lessons ADD COLUMN IF NOT EXISTS video_source TEXT');
    console.log('  ✓ Columns added (or already exist)\n');

    // Step 2: Fetch all lessons with metadata
    console.log('Step 2: Fetching all lessons with course/unit metadata...');
    const result = await pool.query(`
      SELECT l.id, l.title, l.lesson_number,
             u.title as unit_title, u.unit_number,
             c.name as course_name, c.subject, c.grade_level
      FROM lessons l
      JOIN units u ON l.unit_id = u.id
      JOIN courses c ON u.course_id = c.id
      ORDER BY c.grade_level, c.subject, u.unit_number, l.lesson_number
    `);
    console.log(`  ✓ Found ${result.rows.length} lessons\n`);

    // Step 3: Generate and save content
    console.log('Step 3: Generating instructional content for each lesson...');
    let updated = 0, errors = 0;
    let currentSubject = '';

    for (const lesson of result.rows) {
      if (lesson.subject !== currentSubject) {
        currentSubject = lesson.subject;
        console.log(`  Processing: Grade ${lesson.grade_level} ${currentSubject}...`);
      }
      try {
        const c = generateLessonContent(lesson);
        await pool.query(
          `UPDATE lessons SET
             learning_objectives = $1,
             instructional_content = $2,
             vocabulary = $3,
             examples = $4,
             guided_practice = $5
           WHERE id = $6`,
          [
            c.objectives.join('\n'),
            c.content,
            JSON.stringify(c.vocabulary),
            JSON.stringify(c.examples),
            JSON.stringify(c.practice),
            lesson.id
          ]
        );
        updated++;
      } catch (err) {
        errors++;
        console.error(`  ✗ Error on lesson ${lesson.id} (${lesson.title}): ${err.message}`);
      }
    }

    // Summary
    console.log(`\n============================================`);
    console.log('SEED COMPLETE');
    console.log('============================================');
    console.log(`Total lessons: ${result.rows.length}`);
    console.log(`Updated: ${updated}`);
    console.log(`Errors: ${errors}`);
    console.log('');
    console.log('Each lesson now has:');
    console.log('  ✓ Learning objectives (3-5 per lesson)');
    console.log('  ✓ Instructional content (multi-paragraph teaching text)');
    console.log('  ✓ Vocabulary with definitions (4-8 terms)');
    console.log('  ✓ Worked examples (1-2 per lesson)');
    console.log('  ✓ Guided practice with hints (1-2 per lesson)');
    console.log('============================================');

  } catch (err) {
    console.error('Fatal error:', err);
  } finally {
    await pool.end();
  }
}

main();
