const { chromium } = require('playwright');
const path = require('path');

async function sendNote(text) {
  const browser = await chromium.launch({ headless: true });
  const authPath = path.join(__dirname, 'auth.json');
  const context = await browser.newContext({ storageState: authPath });
  const page = await context.newPage();
  
  await page.setViewportSize({ width: 1280, height: 1000 });

  try {
    const targetUrl = 'http://myaff.duckdns.org:3010/workspace/fc2caf2b-3e3e-48cc-9533-4eb63b4753cf/M5HIySO_xVmitXRc3ZjdQ';
    
    console.log('Opening Inbox...');
    await page.goto(targetUrl, { waitUntil: 'domcontentloaded', timeout: 60000 });
    await page.waitForSelector('#app', { timeout: 30000 });
    
    // Crucial: Give the workspace 15s to fully load the existing notes
    console.log('Syncing existing content (15s)...');
    await page.waitForTimeout(15000); 

    // Click center to focus
    await page.mouse.click(640, 400); 
    await page.waitForTimeout(1000);

    // MOVE TO ABSOLUTE BOTTOM
    console.log('Navigating to bottom...');
    await page.keyboard.press('Meta+ArrowDown');
    await page.waitForTimeout(500);
    await page.keyboard.press('Enter');
    await page.keyboard.press('Enter');

    const dateStr = new Date().toLocaleString('en-CA', { 
        dateStyle: 'medium', 
        timeStyle: 'short' 
    });

    // --- SEQUENTIAL FORMATTING ---
    // We type and wait for each block to "register" before moving on
    
    console.log('Injecting Divider...');
    await page.keyboard.type('---');
    await page.keyboard.press('Enter');
    await page.waitForTimeout(1500); // Wait for horizontal line conversion

    console.log('Injecting Heading...');
    // We type '## ' then wait, then the text. The space after ## is the trigger.
    await page.keyboard.type('## ');
    await page.waitForTimeout(500);
    await page.keyboard.type('📝 Note: ' + dateStr);
    await page.keyboard.press('Enter');
    await page.waitForTimeout(1000);

    console.log('Injecting Content...');
    await page.keyboard.type('* ');
    await page.waitForTimeout(500);
    await page.keyboard.type(text);
    await page.keyboard.press('Enter');

    // Final wait to ensure the YJS sync broadcasts the new blocks
    await page.waitForTimeout(7000); 
    console.log('--- Done ---');

  } catch (err) {
    console.error('Error:', err.message);
  } finally {
    await browser.close();
  }
}

const noteText = process.argv[2];
if (noteText) sendNote(noteText);