#!/usr/bin/env raku

use Terminal::UI 'ui';

# ui.log('debug');
ui.setup(ratios => [1,1]);

my $mojo = run
 <<mojo get https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml 'item > title,link' text
  >>,
  :out;

for $mojo.out.lines -> $text, $value {
   ui.panes[1].put("$text", meta => url => ~$value, :!scroll-ok );
}

sub show-article($url) {
  my $proc = run <<w3m -dump $url>>, :out;
  ui.panes[0].clear;
  ui.panes[0].put($url);
  start react whenever $proc.out.lines -> $l {
    ui.panes[0].put($l, :!scroll-ok)
  }
}

ui.panes[0].put("select an article");

ui.focus(pane => 1);

ui.panes[1].register-action(
  :name<launch>,
  action => {
    my $meta = ui.panes[1].current-meta;
    show-article($meta<url>)
  }
);

my $open = trim( qx[which xdg-open] // qx[which open] );
ui.panes[0].register-action(
  :name<launch>,
  action => {
    my $line = ui.panes[0].current-line;
    shell "$open $line 2>/dev/null" if $line ~~ /^^ http/;
  }
);

react whenever ui.keys(done => 'q') {
  ui.focused.select-up when 'k' | 'Up';
  ui.focused.select-down when 'j' | 'Down';
  ui.focused.page-down when ' ' | 'J' | 'PageDown';
  ui.focused.page-up when 'K' | 'PageUp';
  when "Enter" {
    ui.focused.run-action('launch');
  }
  ui.focus(pane => 'next') when "\t";
}

ui.shutdown;
