//
// Library browser. Three scrollable columns: artists | albums | tracks.
// Click an artist → fetch its albums. Click an album → fetch its tracks.
// Click a track → play it (and queue the rest of the album).
//
// Top bar: title + logout. Bottom bar: now-playing strip + transport controls.
//

draw_library_view :: () {
    artist_alpha_jump();

    w := cast(float) app.window_width;
    h := cast(float) app.window_height;

    // Margins.
    pad      := h * 0.02;
    top_h    := h * 0.10;  // header strip
    bottom_h := h * 0.10;  // transport strip

    draw_library_header(0, 0, w, top_h);
    draw_library_columns(pad, top_h, w - pad * 2, h - top_h - bottom_h);
    draw_transport_strip(0, h - bottom_h, w, bottom_h);
}

#scope_file

draw_library_header :: (x: float, y: float, w: float, h: float) {
    label_theme := app.theme.label_theme;
    label_theme.font = app.title_font;
    label_theme.alignment = .Left;
    label_theme.text_color = ifx app.palette_ready then app.palette[1] else Vector4.{1, 0.4, 0.8, 1};
    label(get_rect(x + h * 0.4, y + h * 0.1, w * 0.5, h * 0.8), "CELICA", *label_theme);

    button_theme := app.theme.button_theme;
    button_theme.font = app.button_font;
    button_theme.label_theme.alignment = .Center;

    bh := h * 0.5;
    by := y + h * 0.25;
    bw_sm := w * 0.08;
    bw_lg := w * 0.12;

    // Logout — far right
    if button(get_rect(x + w - bw_sm - h * 0.4, by, bw_sm, bh), "logout", *button_theme, identifier=10) {
        jellyfin_logout(*app.jellyfin);
        free(app.jellyfin.password);
        app.jellyfin.password = copy_string("");
        app.current_view = .LOGIN;
    }

    // Shuffle start buttons — queue current tracks and begin playing shuffled.
    gap := bw_lg * 0.15;
    sfav_x := x + w - bw_sm - bw_lg - h * 0.4 - gap;
    sf_x   := sfav_x - bw_lg - gap;

    if button(get_rect(sfav_x, by, bw_lg, bh), "Shuffle Fav", *button_theme, identifier=12) {
        library_start_global_shuffle(.FAVOURITES);
    }

    if button(get_rect(sf_x, by, bw_lg, bh), "Shuffle", *button_theme, identifier=11) {
        library_start_global_shuffle(.ALL);
    }
}

draw_library_columns :: (x: float, y: float, w: float, h: float) {
    pad := w * 0.01;
    col_w := (w - pad * 2) / 3.0;

    artists_x := x;
    albums_x  := x + col_w + pad;
    tracks_x  := x + col_w * 2 + pad * 2;

    draw_artists_column(artists_x, y, col_w, h);
    draw_albums_column (albums_x,  y, col_w, h);
    draw_tracks_column (tracks_x,  y, col_w, h);
}

draw_artists_column :: (x: float, y: float, w: float, h: float) {
    header_h := app.button_font.character_height * 1.5;
    draw_column_header(x, y, w, header_h, "ARTISTS");

    region_y := y + header_h;
    region_h := h - header_h;
    region, inside := begin_scrollable_region(get_rect(x, region_y, w, region_h));

    button_theme := app.theme.button_theme;
    button_theme.font = app.row_font;
    button_theme.label_theme.alignment = .Left;

    row_h := app.row_font.character_height * 1.8;
    s := inside;
    s.h = row_h;
    s.y -= app.library.artists_scroll;

    for app.library.artists {
        active := app.library.selected_artist_id == it.id;
        bt := button_theme;
        if active {
            bt.surface_color = lib_sel_color();
            bt.text_color    = lib_sel_text();
        }

        thumb_size := row_h;
        thumb_pad  := row_h * 0.10;

        img := image_request(it.id, .THUMB);
        draw_image(s.x, s.y, thumb_size, row_h, img);

        btn_x := s.x + thumb_size + thumb_pad;
        btn_w := s.w - thumb_size - thumb_pad;
        if button(get_rect(btn_x, s.y, btn_w, row_h), it.name, *bt, identifier=it_index) {
            library_select_artist(it.id);
        }
        s.y += row_h * 1.05;
    }

    end_scrollable_region(region, s.x + s.w, s.y, *app.library.artists_scroll);
}

draw_albums_column :: (x: float, y: float, w: float, h: float) {
    header_h := app.button_font.character_height * 1.5;
    draw_column_header(x, y, w, header_h, "ALBUMS");

    region_y := y + header_h;
    region_h := h - header_h;
    region, inside := begin_scrollable_region(get_rect(x, region_y, w, region_h));

    button_theme := app.theme.button_theme;
    button_theme.font = app.row_font;
    button_theme.label_theme.alignment = .Left;

    row_h := app.row_font.character_height * 1.8;
    s := inside;
    s.h = row_h;
    s.y -= app.library.albums_scroll;

    for app.library.albums {
        active := app.library.selected_album_id == it.id;
        bt := button_theme;
        if active {
            bt.surface_color = lib_sel_color();
            bt.text_color    = lib_sel_text();
        }

        thumb_size := row_h;
        thumb_pad  := row_h * 0.10;

        img := image_request(it.id, .THUMB);
        draw_image(s.x, s.y, thumb_size, row_h, img);

        btn_x := s.x + thumb_size + thumb_pad;
        btn_w := s.w - thumb_size - thumb_pad;
        if button(get_rect(btn_x, s.y, btn_w, row_h), it.name, *bt, identifier=it_index) {
            library_select_album(it.id);
        }
        s.y += row_h * 1.05;
    }

    end_scrollable_region(region, s.x + s.w, s.y, *app.library.albums_scroll);
}

draw_tracks_column :: (x: float, y: float, w: float, h: float) {
    header_h := app.button_font.character_height * 1.5;
    draw_column_header(x, y, w, header_h, "TRACKS");

    region_y := y + header_h;
    region_h := h - header_h;
    region, inside := begin_scrollable_region(get_rect(x, region_y, w, region_h));

    button_theme := app.theme.button_theme;
    button_theme.font = app.row_font;
    button_theme.label_theme.alignment = .Left;

    row_h := app.row_font.character_height * 1.8;
    s := inside;
    s.h = row_h;
    s.y -= app.library.tracks_scroll;

    for app.library.tracks {
        playing := app.current_stream && app.current_track.id == it.id;
        bt := button_theme;
        if playing {
            bt.surface_color = lib_play_color();
            bt.text_color    = lib_sel_text();
        }

        label_text := tprint("%. %", it.index_number, it.name);
        if button(s, label_text, *bt, identifier=it_index) {
            queue_clear();
            for tr, idx: app.library.tracks {
                queue_add(tr);
                if tr.id == it.id  queue.current = idx;
            }
            if queue.shuffle_mode != .OFF  queue_rebuild_shuffle();
            audio_play_track(it);
            app.current_view = .NOW_PLAYING;
        }
        s.y += row_h * 1.05;
    }

    end_scrollable_region(region, s.x + s.w, s.y, *app.library.tracks_scroll);
}

draw_column_header :: (x: float, y: float, w: float, h: float, text: string) {
    label_theme := app.theme.label_theme;
    label_theme.font = app.button_font;
    label_theme.alignment = .Left;
    label_theme.text_color = ifx app.palette_ready then app.palette[2] else Vector4.{0.6, 0.9, 1.0, 1};
    label(get_rect(x, y, w, h), text, *label_theme);
}

draw_transport_strip :: (x: float, y: float, w: float, h: float) {
    // Now-playing readout (left).
    label_theme := app.theme.label_theme;
    label_theme.font = app.button_font;
    label_theme.alignment = .Left;
    label_theme.text_color = .{1, 1, 1, 1};

    title := ifx app.current_stream
        then tprint("% — %", app.current_track.artist, app.current_track.name)
        else "—";
    label(get_rect(x + h * 0.3, y + h * 0.2, w * 0.40, h * 0.6), title, *label_theme);

    // Volume slider (middle).
    {
        slider_theme := app.theme.slider_theme;
        slider_theme.foreground.font = app.body_font;

        vw := w * 0.18;
        vh := h * 0.55;
        vx := x + w * 0.42;
        vy := y + h * 0.225;

        before := app.master_volume;
        slider(
            get_rect(vx, vy, vw, vh),
            *app.master_volume,
            0.0, 1.0, 0.05,
            *slider_theme,
            "vol ", "",
            identifier=99,
        );
        if before != app.master_volume  config_save();
    }

    // Transport buttons (right cluster).
    button_theme := app.theme.button_theme;
    button_theme.font = app.button_font;
    button_theme.label_theme.alignment = .Center;

    bw := h * 1.3;
    bh := h * 0.55;
    spacing := h * 0.15;
    cluster_w := bw * 5 + spacing * 4;
    bx := x + w - cluster_w - h * 0.3;
    by := y + h * 0.225;

    shuf_label := ifx queue.shuffle_mode == .OFF then "seq" else ifx queue.shuffle_mode == .ALL then "shuf" else "shuf*";
    if button(get_rect(bx, by, bw, bh), shuf_label, *button_theme) {
        if queue.shuffle_mode == .OFF       queue_set_shuffle(.ALL);
        else if queue.shuffle_mode == .ALL  queue_set_shuffle(.FAVOURITES);
        else                                queue_set_shuffle(.OFF);
    }
    bx += bw + spacing;
    if button(get_rect(bx, by, bw, bh), "<<", *button_theme)  queue_prev();
    bx += bw + spacing;
    pp_label := ifx audio_is_paused() then "PLAY" else "PAUSE";
    if button(get_rect(bx, by, bw, bh), pp_label, *button_theme)  audio_toggle_pause();
    bx += bw + spacing;
    if button(get_rect(bx, by, bw, bh), ">>", *button_theme)  queue_next();
    bx += bw + spacing;
    if button(get_rect(bx, by, bw, bh), "now", *button_theme)  app.current_view = .NOW_PLAYING;
}

#scope_file

// Scroll the artist column to the first artist whose name starts with the
// pressed letter. Works off TEXT_INPUT events so it respects the OS key map.
artist_alpha_jump :: () {
    if !app.library.artists_loaded  return;

    for Input.events_this_frame {
        if it.type != .TEXT_INPUT  continue;

        ch := it.utf32;
        if ch >= 97 && ch <= 122  ch -= 32;   // normalise to upper-case
        if ch < 65  || ch > 90    continue;    // ignore non-letters

        row_h := app.row_font.character_height * 1.8;
        for artist, idx: app.library.artists {
            if artist.name.count == 0  continue;
            name := artist_sort_name(artist.name);
            first := cast(u32) name[0];
            if first >= 97 && first <= 122  first -= 32;
            if first == ch {
                app.library.artists_scroll = cast(float) idx * row_h * 1.05;
                break;
            }
        }
    }
}

// Strip leading articles so "The Beatles" sorts/jumps as "Beatles".
artist_sort_name :: (name: string) -> string {
    if begins_with_nocase(name, "the ") && name.count > 4  return slice(name, 4, name.count - 4);
    if begins_with_nocase(name, "a ")   && name.count > 2  return slice(name, 2, name.count - 2);
    if begins_with_nocase(name, "an ")  && name.count > 3  return slice(name, 3, name.count - 3);
    return name;
}

begins_with_nocase :: (s: string, prefix: string) -> bool {
    if s.count < prefix.count  return false;
    for i: 0..prefix.count-1 {
        sc := s[i];  pc := prefix[i];
        if sc >= #char "A" && sc <= #char "Z"  sc += 32;
        if sc != pc  return false;
    }
    return true;
}

// Selection highlight — palette[1] darkened to read as a background fill.
lib_sel_color :: () -> Vector4 {
    if !app.palette_ready  return .{0.35, 0.10, 0.45, 1};
    p := app.palette[1];
    return .{p.x * 0.40, p.y * 0.40, p.z * 0.40, 1};
}

// Currently-playing highlight — palette[2] darkened, distinct from selection.
lib_play_color :: () -> Vector4 {
    if !app.palette_ready  return .{0.10, 0.40, 0.55, 1};
    p := app.palette[2];
    return .{p.x * 0.38, p.y * 0.38, p.z * 0.38, 1};
}

// Text on a highlighted row — bright version of palette[1].
lib_sel_text :: () -> Vector4 {
    if !app.palette_ready  return .{1, 1, 1, 1};
    p := app.palette[1];
    return .{min(p.x * 1.4 + 0.2, 1), min(p.y * 1.4 + 0.2, 1), min(p.z * 1.4 + 0.2, 1), 1};
}
