#include <stdio.h>
#include <algorithm>
#include <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Choice.H>
#include <FL/Fl_Valuator.H>
#include <FL/Fl_Table.H>
#include <FL/Fl_Tooltip.H>
#include <FL/Fl_Native_File_Chooser.H>
#include <FL/filename.H>
#include <FL/fl_ask.H>
#include <FL/fl_draw.H>
#include "fourier_series.h"
#include "studio_drawing.h"

namespace ui {
const Fl_Color canvas = fl_rgb_color(246, 246, 249);
const Fl_Color paper = fl_rgb_color(255, 255, 255);
const Fl_Color ink = fl_rgb_color(37, 40, 57);
const Fl_Color muted = fl_rgb_color(127, 132, 149);
const Fl_Color line = fl_rgb_color(232, 234, 241);
const Fl_Color accent = fl_rgb_color(116, 93, 224);
const Fl_Color accent_dark = fl_rgb_color(94, 72, 195);
const Fl_Color tint = fl_rgb_color(242, 239, 255);
const Fl_Color target = fl_rgb_color(131, 145, 151);
const Fl_Color green = fl_rgb_color(51, 154, 119);

enum {
    window_w = 1220,
    window_h = 860,
    min_w = 1040,
    min_h = 760,
    margin = 24,
    sidebar_w = 260,
    content_x = 308
};

static void round_fill(int x, int y, int w, int h, int r, Fl_Color color)
{
    drawing::round_rect(x, y, w, h, r, color);
}

static void card(int x, int y, int w, int h)
{
    round_fill(x, y, w, h, 14, line);
    round_fill(x + 1, y + 1, w - 2, h - 2, 13, paper);
}

static void text(const char *s, int x, int y, int size = 13,
                 Fl_Color color = ink, Fl_Font font = FL_HELVETICA)
{
    drawing::font(font, size);
    drawing::color(color);
    drawing::draw(s, x, y);
}

static void triangle_icon(int x, int y, int w, int h)
{
    drawing::line(x, y + h / 2, x + w / 4, y);
    drawing::line(x + w / 4, y, x + 3 * w / 4, y + h);
    drawing::line(x + 3 * w / 4, y + h, x + w, y + h / 2);
}

static void wave_icon(int x, int y, int w, int h, int wave, Fl_Color color)
{
    drawing::color(color);
    drawing::line_style(FL_SOLID, 2);
    if (wave == fourier::SQUARE) {
        drawing::line(x, y + h, x, y);
        drawing::line(x, y, x + w / 2, y);
        drawing::line(x + w / 2, y, x + w / 2, y + h);
        drawing::line(x + w / 2, y + h, x + w, y + h);
        drawing::line(x + w, y + h, x + w, y);
    } else if (wave == fourier::SAWTOOTH) {
        drawing::line(x, y + h, x + w / 2, y);
        drawing::line(x + w / 2, y, x + w / 2, y + h);
        drawing::line(x + w / 2, y + h, x + w, y);
    } else
        triangle_icon(x, y, w, h);
    drawing::line_style(0);
}
} // namespace ui

class Header : public Fl_Widget {
protected:
    void draw_logo()
    {
        ui::round_fill(24, 28, 40, 40, 12, ui::accent);
        drawing::color(ui::paper);
        drawing::line_style(FL_SOLID, 2);
        for (int i = 1; i <= 28; ++i) {
            double y0 = 48 - 9 * std::sin((i - 1) * 2 * fourier::pi / 28);
            double y1 = 48 - 9 * std::sin(i * 2 * fourier::pi / 28);
            drawing::line(30 + i - 1, y0, 30 + i, y1);
        }
        drawing::line_style(0);
    }

    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        drawing::color(ui::canvas);
        drawing::rectf(x(), y(), w(), h());
        draw_logo();
        ui::text("Fourier Studio", 80, 46, 25, ui::ink, FL_HELVETICA_BOLD);
        ui::text("A signal playground. Build something from a little sine.", 81,
                 69, 13, ui::muted);
        ui::round_fill(w() - 306, 37, 130, 26, 13, fl_rgb_color(233, 247, 241));
        drawing::color(ui::green);
        drawing::pie(w() - 292, 47, 6, 6, 0, 360);
        ui::text("INTERACTIVE", w() - 278, 54, 10, ui::green,
                 FL_HELVETICA_BOLD);
        drawing::pop_clip();
    }

public:
    Header() : Fl_Widget(0, 0, ui::window_w, 90) {}
};

class Sidebar : public Fl_Group {
    const fourier::Series *series_;

protected:
    void draw_hints()
    {
        const char *hints[] = { "Sharp edges. Odd harmonics.",
                                "A ramp. Every harmonic.",
                                "Soft corners. Fast convergence." };
        ui::text(hints[series_->waveform()], x() + 22, y() + 587, 12, ui::ink);
        ui::text("Try adding a few more harmonics.", x() + 22, y() + 607, 11,
                 ui::muted);
        if (h() > 680)
            ui::text("Space: animate   Ctrl+E: export", x() + 22,
                     y() + h() - 24, 11, ui::muted);
    }

    void draw_panel()
    {
        ui::card(x(), y(), w(), h());
        ui::text("YOUR SIGNAL", x() + 22, y() + 29, 11, ui::muted,
                 FL_HELVETICA_BOLD);
        drawing::color(ui::line);
        drawing::line(x() + 22, y() + 142, x() + w() - 22, y() + 142);
        ui::text("SAMPLE RESOLUTION", x() + 22, y() + 409, 11, ui::muted,
                 FL_HELVETICA_BOLD);
        drawing::color(ui::line);
        drawing::line(x() + 22, y() + 563, x() + w() - 22, y() + 563);
        draw_hints();
    }

    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        if (damage() & ~FL_DAMAGE_CHILD)
            draw_panel();
        drawing::flush();
        draw_children();
        drawing::pop_clip();
    }

public:
    Sidebar(const fourier::Series *series)
        : Fl_Group(24, 104, ui::sidebar_w, ui::window_h - 128), series_(series)
    {
        resizable(0);
    }
};

class WaveSelector : public Fl_Widget {
    int value_;

protected:
    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        drawing::color(ui::paper);
        drawing::rectf(x(), y(), w(), h());
        const char *names[] = { "Square", "Sawtooth", "Triangle" };
        for (int i = 0; i < 3; ++i) {
            int X = x() + i * (w() + 6) / 3;
            int W = (w() - 12) / 3;
            bool selected = i == value_;
            ui::round_fill(X, y(), W, h(), 10,
                           selected ? ui::accent : ui::line);
            ui::round_fill(X + 1, y() + 1, W - 2, h() - 2, 9,
                           selected ? ui::tint : ui::paper);
            ui::wave_icon(X + W / 2 - 17, y() + 17, 34, 20, i,
                          selected ? ui::accent : ui::target);
            drawing::font(selected ? FL_HELVETICA_BOLD : FL_HELVETICA, 11);
            drawing::color(selected ? ui::accent : ui::muted);
            drawing::draw(names[i], X, y() + 48, W, 19, FL_ALIGN_CENTER);
        }
        drawing::pop_clip();
    }

public:
    WaveSelector() : Fl_Widget(46, 160, 216, 76), value_(0) {}
    int value() const { return value_; }
    void value(int n)
    {
        value_ = n;
        redraw();
    }

private:
    void select_from_mouse()
    {
        int n = std::min(2, std::max(0, (Fl::event_x() - x()) * 3 / w()));
        if (n != value_) {
            value(n);
            do_callback();
        }
    }

public:
    int handle(int event)
    {
        if (event == FL_PUSH) {
            take_focus();
            select_from_mouse();
            return 1;
        }
        if (event == FL_KEYDOWN
            && (Fl::event_key() == FL_Left || Fl::event_key() == FL_Right)) {
            value((value_ + (Fl::event_key() == FL_Right ? 1 : 2)) % 3);
            do_callback();
            return 1;
        }
        if (event == FL_FOCUS || event == FL_UNFOCUS) {
            redraw();
            return 1;
        }
        return 0;
    }
};

class StudioSlider : public Fl_Valuator {
    int format_;
    bool dragging_;
    void from_mouse()
    {
        double fraction =
            static_cast<double>(Fl::event_x() - x() - 7) / (w() - 14);
        fraction = std::max(0.0, std::min(1.0, fraction));
        handle_drag(
            clamp(round(minimum() + fraction * (maximum() - minimum()))));
    }

protected:
    void draw_value()
    {
        char text[40];
        if (format_ == 0)
            snprintf(text, sizeof(text), "%.2f", value());
        else if (format_ == 1)
            snprintf(text, sizeof(text), "%.0f°", value());
        else
            snprintf(text, sizeof(text), "%.0f", value());
        ui::round_fill(x() + w() - 58, y(), 58, 25, 7, ui::tint);
        drawing::font(FL_HELVETICA_BOLD, 12);
        drawing::color(ui::accent);
        drawing::draw(text, x() + w() - 58, y(), 58, 25, FL_ALIGN_CENTER);
    }

    void draw_track()
    {
        int left = x() + 7, width = w() - 14;
        int position = left
                       + static_cast<int>(width * (value() - minimum())
                                          / (maximum() - minimum()));
        ui::round_fill(left, y() + 43, width, 5, 2, ui::line);
        if (position > left)
            ui::round_fill(left, y() + 43, position - left, 5, 2, ui::accent);
        drawing::color(ui::accent);
        drawing::pie(position - 8, y() + 37, 16, 16, 0, 360);
        drawing::color(ui::paper);
        drawing::pie(position - 5, y() + 40, 10, 10, 0, 360);
    }

    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        drawing::color(ui::paper);
        drawing::rectf(x(), y(), w(), h());
        ui::text(label(), x(), y() + 17, 13, ui::ink, FL_HELVETICA_BOLD);
        draw_value();
        draw_track();
        if (Fl::focus() == this) {
            drawing::color(ui::accent);
            drawing::line(x(), y() + h() - 1, x() + w(), y() + h() - 1);
        }
        drawing::pop_clip();
    }

public:
    StudioSlider(int Y, const char *label, int format)
        : Fl_Valuator(46, Y, 216, 62, label), format_(format), dragging_(false)
    {
        align(FL_ALIGN_INSIDE);
        when(FL_WHEN_CHANGED);
    }

private:
    void begin_drag()
    {
        take_focus();
        dragging_ = true;
        handle_push();
        from_mouse();
    }

    int handle_mouse(int event)
    {
        if (event == FL_PUSH)
            begin_drag();
        else if (event == FL_DRAG) {
            if (dragging_)
                from_mouse();
        } else {
            dragging_ = false;
            handle_release();
        }
        return 1;
    }

    void step_by_key(int direction)
    {
        handle_push();
        handle_drag(clamp(increment(value(), direction)));
        handle_release();
    }

    void jump_by_key(int key)
    {
        handle_push();
        handle_drag(key == FL_Home ? minimum() : maximum());
        handle_release();
    }

    int handle_key()
    {
        int key = Fl::event_key();
        if (key == FL_Left || key == FL_Right || key == FL_Up
            || key == FL_Down) {
            int direction = key == FL_Right || key == FL_Up ? 1 : -1;
            step_by_key(direction);
            return 1;
        }
        if (key == FL_Home || key == FL_End) {
            jump_by_key(key);
            return 1;
        }
        return 0;
    }

public:
    int handle(int event)
    {
        if (event == FL_PUSH || event == FL_DRAG || event == FL_RELEASE)
            return handle_mouse(event);
        if (event == FL_KEYDOWN)
            return handle_key();
        if (event == FL_FOCUS || event == FL_UNFOCUS) {
            redraw();
            return 1;
        }
        return 0;
    }
};

class SampleChoice : public Fl_Choice {
protected:
    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        ui::round_fill(x(), y(), w(), h(), 9,
                       Fl::focus() == this ? ui::accent : ui::line);
        ui::round_fill(x() + 1, y() + 1, w() - 2, h() - 2, 8, ui::paper);
        ui::text(text(), x() + 14, y() + 26, 13);
        drawing::color(ui::muted);
        drawing::line(x() + w() - 25, y() + 17, x() + w() - 20, y() + 22,
                      x() + w() - 15, y() + 17);
        drawing::pop_clip();
    }

public:
    SampleChoice() : Fl_Choice(46, 538, 216, 42)
    {
        add("256 samples|512 samples|1,024 samples|2,048 samples");
        value(2);
        textsize(13);
        color(ui::paper);
        textcolor(ui::ink);
        selection_color(ui::accent);
    }
};

class ActionButton : public Fl_Button {
    bool primary_, hover_;
    int icon_;

protected:
    void draw_background()
    {
        Fl_Color fill = primary_
                            ? (value() || hover_ ? ui::accent_dark : ui::accent)
                            : ui::paper;
        if (!active_r())
            fill = ui::line;
        ui::round_fill(x(), y(), w(), h(), 10, primary_ ? fill : ui::line);
        if (!primary_)
            ui::round_fill(x() + 1, y() + 1, w() - 2, h() - 2, 9,
                           hover_ ? ui::canvas : fill);
    }

    void draw_play_icon()
    {
        if (label()[0] == 'P') {
            drawing::rectf(x() + 18, y() + h() / 2 - 5, 3, 10);
            drawing::rectf(x() + 24, y() + h() / 2 - 5, 3, 10);
        } else {
            drawing::polygon(x() + 18, y() + h() / 2 - 5, x() + 18,
                             y() + h() / 2 + 5, x() + 26, y() + h() / 2);
        }
    }

    void draw_download_icon()
    {
        int X = x() + 20, Y = y() + h() / 2;
        drawing::line(X, Y - 7, X, Y + 3);
        drawing::line(X - 4, Y - 1, X, Y + 3, X + 4, Y - 1);
        drawing::line(X - 6, Y + 7, X + 6, Y + 7);
    }

    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        draw_background();
        drawing::font(FL_HELVETICA_BOLD, 13);
        drawing::color(primary_ && active_r()
                           ? ui::paper
                           : (active_r() ? ui::ink : ui::muted));
        if (icon_ == 1)
            draw_play_icon();
        else if (icon_ == 2)
            draw_download_icon();
        drawing::draw(label(), x() + (icon_ ? 15 : 0), y(),
                      w() - (icon_ ? 15 : 0), h(), FL_ALIGN_CENTER);
        if (Fl::focus() == this) {
            drawing::color(primary_ ? ui::paper : ui::accent);
            drawing::line(x() + 14, y() + h() - 7, x() + w() - 14,
                          y() + h() - 7);
        }
        drawing::pop_clip();
    }

public:
    ActionButton(int X, int Y, int W, int H, const char *label, bool primary,
                 bool export_icon = false)
        : Fl_Button(X, Y, W, H, label), primary_(primary), hover_(false),
          icon_(primary ? 1 : (export_icon ? 2 : 0))
    {}
    int handle(int event)
    {
        if (event == FL_ENTER || event == FL_LEAVE) {
            hover_ = event == FL_ENTER;
            redraw();
        }
        return Fl_Button::handle(event);
    }
};

class Metric : public Fl_Widget {
    char value_[48], hint_[96];

protected:
    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        ui::card(x(), y(), w(), h());
        ui::text(label(), x() + 20, y() + 24, 10, ui::muted, FL_HELVETICA_BOLD);
        ui::text(value_, x() + 20, y() + 59, 28, ui::ink, FL_HELVETICA_BOLD);
        ui::text(hint_, x() + 20, y() + 79, 11, ui::muted);
        drawing::pop_clip();
    }

public:
    Metric(const char *label) : Fl_Widget(0, 104, 200, 96, label)
    {
        value_[0] = hint_[0] = '\0';
    }
    void display(const char *value, const char *hint)
    {
        snprintf(value_, sizeof(value_), "%s", value);
        snprintf(hint_, sizeof(hint_), "%s", hint);
        redraw();
    }
};

class WaveformPlot : public Fl_Widget {
    const fourier::Series *series_;
    int hover_, requested_;
    bool playing_;
    int graph_x() const { return x() + 60; }
    int graph_y() const { return y() + 82; }
    int graph_w() const { return w() - 86; }
    int graph_h() const { return h() - 123; }
    double point_y(double value) const
    {
        return graph_y()
               + graph_h() * (0.5 - value / (2.9 * series_->amplitude()));
    }

protected:
    void draw_header()
    {
        ui::text("Waveform reconstruction", x() + 22, y() + 31, 17, ui::ink,
                 FL_HELVETICA_BOLD);
        char subtitle[120];
        const char *state = playing_ ? "building the series…" : "one period";
        snprintf(subtitle, sizeof(subtitle),
                 "%s wave  ·  %d / %d harmonics  ·  %s",
                 fourier::name(series_->waveform()), series_->terms(),
                 requested_, state);
        ui::text(subtitle, x() + 22, y() + 52, 11, ui::muted);
    }

    void draw_legend()
    {
        drawing::color(ui::target);
        drawing::line_style(FL_DASH, 1);
        drawing::line(x() + w() - 246, y() + 28, x() + w() - 226, y() + 28);
        drawing::line_style(0);
        ui::text("Target", x() + w() - 218, y() + 32, 11, ui::muted);
        drawing::color(ui::accent);
        drawing::line_style(FL_SOLID, 2);
        drawing::line(x() + w() - 158, y() + 28, x() + w() - 138, y() + 28);
        drawing::line_style(0);
        ui::text("Fourier series", x() + w() - 130, y() + 32, 11, ui::accent);
    }

    double point_x(int sample) const
    {
        return graph_x()
               + static_cast<double>(graph_w()) * sample / series_->samples();
    }

    bool has_hover() const
    {
        return hover_ >= 0 && hover_ < series_->samples();
    }

    void draw_fill()
    {
        drawing::color(fl_rgb_color(248, 246, 255));
        drawing::begin_complex_polygon();
        drawing::vertex(graph_x(), point_y(0));
        for (int i = 0; i <= series_->samples(); ++i)
            drawing::vertex(point_x(i), point_y(series_->approximation(
                                            i % series_->samples())));
        drawing::vertex(graph_x() + graph_w(), point_y(0));
        drawing::end_complex_polygon();
    }

    void draw_grid()
    {
        int X = graph_x(), Y = graph_y(), W = graph_w(), H = graph_h();
        for (int i = -2; i <= 2; ++i) {
            drawing::color(i ? ui::line : fl_rgb_color(214, 216, 229));
            int yy = static_cast<int>(point_y(series_->amplitude() * i / 2.0));
            drawing::line(X, yy, X + W, yy);
        }
        for (int i = 0; i < 5; ++i) {
            drawing::color(ui::line);
            drawing::line(X + W * i / 4, Y, X + W * i / 4, Y + H);
        }
    }

    void draw_curve(int curve)
    {
        drawing::color(curve ? ui::accent : ui::target);
        drawing::line_style(curve ? FL_SOLID : FL_DASH, curve ? 2 : 1);
        drawing::begin_line();
        for (int i = 0; i <= series_->samples(); ++i) {
            int sample = i % series_->samples();
            drawing::vertex(point_x(i),
                            point_y(curve ? series_->approximation(sample)
                                          : series_->target(sample)));
        }
        drawing::end_line();
    }

    void draw_hover_point()
    {
        int hx = graph_x() + graph_w() * hover_ / series_->samples();
        int hy = static_cast<int>(point_y(series_->approximation(hover_)));
        drawing::color(ui::accent);
        drawing::line_style(FL_DOT, 1);
        drawing::line(hx, graph_y(), hx, graph_y() + graph_h());
        drawing::line_style(0);
        drawing::color(ui::paper);
        drawing::pie(hx - 5, hy - 5, 10, 10, 0, 360);
        drawing::color(ui::accent);
        drawing::pie(hx - 3, hy - 3, 6, 6, 0, 360);
    }

    void draw_vertical_ticks()
    {
        for (int i = -2; i <= 2; ++i) {
            char text[32];
            double value = series_->amplitude() * i / 2.0;
            snprintf(text, sizeof(text), "%.2g", value);
            drawing::font(FL_HELVETICA, 11);
            drawing::color(ui::muted);
            drawing::draw(text, x() + 10, static_cast<int>(point_y(value)) - 8,
                          39, 16, FL_ALIGN_RIGHT);
        }
    }

    void draw_horizontal_ticks()
    {
        const char *ticks[] = { "-π", "-π/2", "0", "π/2", "π" };
        for (int i = 0; i < 5; ++i) {
            drawing::font(FL_HELVETICA, 11);
            drawing::color(ui::muted);
            drawing::draw(ticks[i], graph_x() + graph_w() * i / 4 - 22,
                          graph_y() + graph_h() + 14, 44, 18, FL_ALIGN_CENTER);
        }
    }

    void draw_readout()
    {
        int bx =
            std::min(graph_x() + graph_w() - 180,
                     graph_x() + graph_w() * hover_ / series_->samples() + 14);
        int by = graph_y() + 10;
        ui::round_fill(bx, by, 180, 76, 10, ui::ink);
        char text[64];
        snprintf(text, sizeof(text), "x = %.3f", series_->x(hover_));
        ui::text(text, bx + 12, by + 21, 11, ui::paper, FL_HELVETICA_BOLD);
        snprintf(text, sizeof(text), "Target      % .4f",
                 series_->target(hover_));
        ui::text(text, bx + 12, by + 43, 11, fl_rgb_color(204, 211, 220));
        snprintf(text, sizeof(text), "Series       % .4f",
                 series_->approximation(hover_));
        ui::text(text, bx + 12, by + 62, 11, fl_rgb_color(194, 180, 255));
    }

    void draw_graph()
    {
        drawing::push_clip(graph_x(), graph_y(), graph_w() + 1, graph_h() + 1);
        draw_fill();
        draw_grid();
        draw_curve(0);
        draw_curve(1);
        drawing::line_style(0);
        if (has_hover())
            draw_hover_point();
        drawing::pop_clip();
        draw_vertical_ticks();
        draw_horizontal_ticks();
        if (has_hover())
            draw_readout();
    }

    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        ui::card(x(), y(), w(), h());
        draw_header();
        draw_legend();
        if (series_->samples())
            draw_graph();
        drawing::pop_clip();
    }

public:
    WaveformPlot(const fourier::Series *series)
        : Fl_Widget(0, 0, 700, 390), series_(series), hover_(-1),
          requested_(15), playing_(false)
    {}
    void state(bool playing, int requested)
    {
        playing_ = playing;
        requested_ = requested;
        hover_ = -1;
        redraw();
    }

private:
    void update_hover()
    {
        if (Fl::event_x() >= graph_x() && Fl::event_x() <= graph_x() + graph_w()
            && Fl::event_y() >= graph_y()
            && Fl::event_y() <= graph_y() + graph_h()) {
            hover_ = std::min(series_->samples() - 1,
                              (Fl::event_x() - graph_x()) * series_->samples()
                                  / graph_w());
        } else
            hover_ = -1;
        redraw();
    }

public:
    int handle(int event)
    {
        if (event == FL_MOVE || event == FL_ENTER) {
            update_hover();
            return 1;
        }
        if (event == FL_LEAVE) {
            hover_ = -1;
            redraw();
            return 1;
        }
        return 0;
    }
};

class Spectrum : public Fl_Widget {
    const fourier::Series *series_;
    int requested_;

protected:
    double harmonic_amplitude(int i) const
    {
        const fourier::Harmonic &term = series_->harmonic(i);
        return std::sqrt(term.cosine * term.cosine + term.sine * term.sine);
    }

    double maximum_amplitude() const
    {
        double maximum = 0.0;
        for (int i = 0; i < series_->terms(); ++i)
            maximum = std::max(maximum, harmonic_amplitude(i));
        return maximum;
    }

    void draw_grid()
    {
        int left = x() + 22, top = y() + 18;
        int width = w() - 36, height = h() - 45;
        for (int i = 0; i < 3; ++i) {
            drawing::color(ui::line);
            drawing::line(left, top + height * i / 2, left + width,
                          top + height * i / 2);
        }
    }

    void draw_peak(int center, int top, double amplitude)
    {
        char text[24];
        snprintf(text, sizeof(text), "%.3f", amplitude);
        drawing::font(FL_HELVETICA_BOLD, 10);
        drawing::color(ui::accent);
        drawing::draw(text, center - 30, top - 22, 60, 18, FL_ALIGN_CENTER);
    }

    void draw_bar(int i, int center, double maximum, double scale)
    {
        if (i >= series_->terms())
            return;
        int bins = std::max(16, requested_);
        int bar_w = std::max(2, std::min(20, (w() - 36) / bins - 5));
        double amplitude = harmonic_amplitude(i);
        int bar_h = static_cast<int>((h() - 45) * amplitude / scale);
        if (bar_h <= 1)
            return;
        int top = y() + 18 + h() - 45 - bar_h;
        ui::round_fill(center - bar_w / 2, top, bar_w, bar_h,
                       std::min(4, bar_w / 2), ui::accent);
        if (amplitude > maximum * 0.99)
            draw_peak(center, top, amplitude);
    }

    void draw_bin_label(int i, int center, int bins)
    {
        bool tick = i == 0 || i == bins - 1
                    || (bins <= 24 ? (i + 1) % 4 == 0 : (i + 1) % 10 == 0);
        if (!tick)
            return;
        char text[24];
        snprintf(text, sizeof(text), "%d", i + 1);
        drawing::font(FL_HELVETICA, 10);
        drawing::color(ui::muted);
        drawing::draw(text, center - 18, y() + 18 + h() - 45 + 8, 36, 17,
                      FL_ALIGN_CENTER);
    }

    void draw_bars(double maximum, double scale)
    {
        int bins = std::max(16, requested_);
        int left = x() + 22, width = w() - 36;
        for (int i = 0; i < bins; ++i) {
            int center = left + width * (2 * i + 1) / (2 * bins);
            draw_bar(i, center, maximum, scale);
            draw_bin_label(i, center, bins);
        }
    }

    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        drawing::color(ui::paper);
        drawing::rectf(x(), y(), w(), h());
        double maximum = maximum_amplitude();
        double scale = maximum > 1e-12 ? maximum * 1.25 : 1.0;
        draw_grid();
        draw_bars(maximum, scale);
        drawing::pop_clip();
    }

public:
    Spectrum(const fourier::Series *series)
        : Fl_Widget(0, 0, 700, 150), series_(series), requested_(15)
    {}
    void requested(int n)
    {
        requested_ = n;
        redraw();
    }
};

class CoefficientTable : public Fl_Table {
    const fourier::Series *series_;

protected:
    double cell_value(int r, int c) const
    {
        const fourier::Harmonic &term = series_->harmonic(r);
        double value = c == 1 ? term.cosine : (c == 2 ? term.sine : term.rmse);
        return std::fabs(value) < 0.000005 ? 0.0 : value;
    }

    void cell_text(char *text, size_t size, TableContext context, int r,
                   int c) const
    {
        if (context == CONTEXT_COL_HEADER) {
            const char *titles[] = { "HARMONIC", "COSINE  a_n", "SINE  b_n",
                                     "RMS ERROR" };
            snprintf(text, size, "%s", titles[c]);
        } else if (c == 0)
            snprintf(text, size, "%02d", r + 1);
        else if (r < series_->terms())
            snprintf(text, size, "%.5f", cell_value(r, c));
        else
            snprintf(text, size, "-");
    }

    void draw_background(TableContext context, int r, int c, int X, int Y,
                         int W, int H)
    {
        drawing::color(context == CONTEXT_COL_HEADER
                           ? ui::canvas
                           : (is_selected(r, c) ? ui::tint : ui::paper));
        drawing::rectf(X, Y, W, H);
        drawing::color(ui::line);
        drawing::line(X, Y + H - 1, X + W, Y + H - 1);
    }

    void draw_content(TableContext context, int r, int c, int X, int Y, int W,
                      int H)
    {
        char text[80];
        cell_text(text, sizeof(text), context, r, c);
        drawing::font(context == CONTEXT_COL_HEADER ? FL_HELVETICA_BOLD
                                                    : FL_HELVETICA,
                      context == CONTEXT_COL_HEADER ? 10 : 12);
        drawing::color(context == CONTEXT_COL_HEADER || r >= series_->terms()
                           ? ui::muted
                           : ui::ink);
        drawing::draw(text, X + 10, Y, W - 20, H, FL_ALIGN_LEFT);
    }

    void draw_cell(TableContext context, int r, int c, int X, int Y, int W,
                   int H)
    {
        if (context != CONTEXT_COL_HEADER && context != CONTEXT_CELL)
            return;
        drawing::Scope paint(this);
        drawing::push_clip(X, Y, W, H);
        draw_background(context, r, c, X, Y, W, H);
        draw_content(context, r, c, X, Y, W, H);
        drawing::pop_clip();
    }

public:
    CoefficientTable(const fourier::Series *series)
        : Fl_Table(0, 0, 700, 150), series_(series)
    {
        cols(4);
        rows(0);
        col_header(1);
        col_header_height(29);
        box(FL_NO_BOX); // Filled boxes would cover the table's scrollbars.
        color(ui::paper);
        vscrollbar->color(ui::canvas);
        vscrollbar->selection_color(fl_rgb_color(207, 208, 224));
        hscrollbar->color(ui::canvas);
        hscrollbar->selection_color(fl_rgb_color(207, 208, 224));
        end();
    }
    void resize(int X, int Y, int W, int H)
    {
        Fl_Table::resize(X, Y, W, H);
        col_width(0, 115);
        int remaining = W - 115 - Fl::scrollbar_size();
        col_width(1, remaining / 3);
        col_width(2, remaining / 3);
        col_width(3, remaining - 2 * (remaining / 3));
    }
    void reset(int count)
    {
        rows(count);
        row_height_all(31);
        row_position(0);
        redraw();
    }
};

class ViewToggle : public Fl_Widget {
    int value_;

protected:
    void draw()
    {
        drawing::Scope paint(this);
        ui::round_fill(x(), y(), w(), h(), 9, ui::canvas);
        int selected_x = x() + value_ * (w() / 2);
        ui::round_fill(selected_x + 3, y() + 3, w() / 2 - 6, h() - 6, 7,
                       ui::paper);
        const char *labels[] = { "Spectrum", "Coefficients" };
        for (int i = 0; i < 2; ++i) {
            drawing::font(i == value_ ? FL_HELVETICA_BOLD : FL_HELVETICA, 11);
            drawing::color(i == value_ ? ui::ink : ui::muted);
            drawing::draw(labels[i], x() + w() * i / 2, y(), w() / 2, h(),
                          FL_ALIGN_CENTER);
        }
    }

public:
    ViewToggle() : Fl_Widget(0, 0, 228, 34), value_(0) {}
    int value() const { return value_; }
    void value(int n)
    {
        value_ = n;
        redraw();
    }
    int handle(int event)
    {
        if (event == FL_PUSH) {
            take_focus();
            value(Fl::event_x() >= x() + w() / 2 ? 1 : 0);
            do_callback();
            return 1;
        }
        if (event == FL_KEYDOWN
            && (Fl::event_key() == FL_Left || Fl::event_key() == FL_Right)) {
            value(1 - value_);
            do_callback();
            return 1;
        }
        if (event == FL_FOCUS || event == FL_UNFOCUS)
            return 1;
        return 0;
    }
};

class Inspector : public Fl_Group {
    static void view_cb(Fl_Widget *, void *data)
    {
        Inspector *panel = static_cast<Inspector*>(data);
        if (panel->toggle->value()) {
            panel->spectrum->hide();
            panel->table->show();
        } else {
            panel->table->hide();
            panel->spectrum->show();
        }
        panel->redraw();
    }

protected:
    void draw()
    {
        drawing::Scope paint(this);
        drawing::push_clip(x(), y(), w(), h());
        // A child can redraw only a few table cells. Preserve the existing
        // background and other cells unless the entire panel is damaged.
        if (damage() & ~FL_DAMAGE_CHILD) {
            ui::card(x(), y(), w(), h());
            ui::text(toggle->value() ? "Inside the series"
                                     : "Frequency spectrum",
                     x() + 22, y() + 30, 16, ui::ink, FL_HELVETICA_BOLD);
            ui::text(toggle->value()
                         ? "Coefficients and error after each harmonic."
                         : "Each bar is the strength of a harmonic.",
                     x() + 22, y() + 50, 11, ui::muted);
        }
        drawing::flush();
        draw_children();
        drawing::pop_clip();
    }

public:
    ViewToggle *toggle;
    Spectrum *spectrum;
    CoefficientTable *table;
    Inspector(const fourier::Series *series) : Fl_Group(0, 0, 700, 220)
    {
        toggle = new ViewToggle();
        toggle->callback(view_cb, this);
        spectrum = new Spectrum(series);
        table = new CoefficientTable(series);
        table->hide();
        end();
    }
    void resize(int X, int Y, int W, int H)
    {
        Fl_Widget::resize(X, Y, W, H);
        toggle->resize(X + W - 250, Y + 17, 228, 34);
        spectrum->resize(X + 16, Y + 65, W - 32, H - 78);
        table->resize(X + 16, Y + 65, W - 32, H - 81);
        redraw();
    }
};

struct App {
    fourier::Series series;
    Header *header;
    Sidebar *sidebar;
    WaveSelector *waveform;
    StudioSlider *amplitude, *phase, *harmonics;
    SampleChoice *samples;
    ActionButton *animate, *reset, *save;
    Metric *error, *energy, *terms;
    WaveformPlot *plot;
    Inspector *inspector;
    int requested;
    bool playing;
    App() : requested(15), playing(false) {}
};

static void animation_tick(void *data);

static double captured_energy(const fourier::Series &series)
{
    double energy = 0.0;
    for (int i = 0; i < series.samples(); ++i)
        energy += series.target(i) * series.target(i);
    if (energy == 0.0)
        return 100.0;
    double remaining = series.rmse() * series.rmse() * series.samples();
    return std::max(0.0, std::min(100.0, 100.0 * (1.0 - remaining / energy)));
}

static void refresh(App *a)
{
    char value[48];
    snprintf(value, sizeof(value), "%.4f", a->series.rmse());
    a->error->display(value, "sampled difference from target");
    snprintf(value, sizeof(value), "%.1f%%", captured_energy(a->series));
    a->energy->display(value, "of the sampled signal");
    if (a->series.terms() == a->requested)
        snprintf(value, sizeof(value), "%d", a->requested);
    else
        snprintf(value, sizeof(value), "%d / %d", a->series.terms(),
                 a->requested);
    a->terms->display(value, "sine + cosine frequency pairs");
    a->animate->copy_label(
        a->playing
            ? "Pause"
            : (a->series.terms() < a->requested ? "Continue" : "Animate"));
    a->plot->state(a->playing, a->requested);
    a->inspector->spectrum->requested(a->requested);
    a->inspector->table->redraw();
    a->sidebar->redraw();
}

static void begin_series(App *a)
{
    a->requested = static_cast<int>(a->harmonics->value());
    a->series.reset(static_cast<fourier::Waveform>(a->waveform->value()),
                    a->amplitude->value(),
                    a->phase->value() * fourier::pi / 180.0,
                    256 << a->samples->value());
    a->inspector->table->reset(a->requested);
}

static void rebuild(App *a)
{
    a->playing = false;
    Fl::remove_timeout(animation_tick, a);
    begin_series(a);
    for (int i = 0; i < a->requested; ++i)
        a->series.add_harmonic();
    refresh(a);
}

static void settings_cb(Fl_Widget *, void *data)
{
    rebuild(static_cast<App*>(data));
}

static void animate_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    Fl::remove_timeout(animation_tick, a);
    if (a->playing)
        a->playing = false;
    else {
        if (a->series.terms() >= a->requested)
            begin_series(a);
        a->playing = true;
        Fl::add_timeout(0.075, animation_tick, a);
    }
    refresh(a);
}

static void animation_tick(void *data)
{
    App *a = static_cast<App*>(data);
    if (!a->playing)
        return;
    if (!a->series.add_harmonic() || a->series.terms() >= a->requested)
        a->playing = false;
    else
        Fl::repeat_timeout(0.075, animation_tick, a);
    refresh(a);
}

static void reset_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    a->waveform->value(0);
    a->amplitude->value(1.0);
    a->phase->value(0.0);
    a->harmonics->value(15);
    a->samples->value(2);
    rebuild(a);
}

static bool write_csv(FILE *file, const fourier::Series &series)
{
    if (fprintf(file, "x,target,approximation,error\n") < 0)
        return false;
    for (int i = 0; i < series.samples(); ++i) {
        if (fprintf(file, "%.17g,%.17g,%.17g,%.17g\n", series.x(i),
                    series.target(i), series.approximation(i),
                    series.target(i) - series.approximation(i))
            < 0)
            return false;
    }
    return true;
}

static void configure_export(Fl_Native_File_Chooser &chooser)
{
    chooser.title("Export Fourier samples");
    chooser.type(Fl_Native_File_Chooser::BROWSE_SAVE_FILE);
    chooser.options(Fl_Native_File_Chooser::SAVEAS_CONFIRM);
    chooser.filter("CSV files\t*.csv");
    chooser.preset_file("fourier_samples.csv");
    char directory[FL_PATH_MAX];
    fl_filename_absolute(directory, sizeof(directory), ".");
    chooser.directory(directory);
}

static void export_csv(const char *path, const fourier::Series &series)
{
    FILE *file = fopen(path, "w");
    if (!file) {
        fl_alert("Could not open the CSV file for writing.");
        return;
    }
    bool ok = write_csv(file, series);
    if (fclose(file) != 0)
        ok = false;
    if (!ok)
        fl_alert("Could not finish writing the CSV file.");
}

static void save_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    // The chooser runs a nested event loop. Export a consistent snapshot.
    const fourier::Series snapshot = a->series;
    Fl_Native_File_Chooser chooser;
    configure_export(chooser);
    int result = chooser.show();
    if (result == 1)
        return;
    if (result == -1) {
        fl_alert("Could not open the file chooser: %s", chooser.errmsg());
        return;
    }
    export_csv(chooser.filename(), snapshot);
}

static void close_cb(Fl_Widget *widget, void *data)
{
    App *a = static_cast<App*>(data);
    a->playing = false;
    Fl::remove_timeout(animation_tick, a);
    widget->hide();
}

static void layout(App &a, int width, int height)
{
    a.header->resize(0, 0, width, 90);
    a.sidebar->resize(24, 104, ui::sidebar_w, height - 128);
    a.save->resize(width - 160, 28, 136, 42);
    int content_w = width - ui::content_x - ui::margin;
    int metric_w = (content_w - 32) / 3;
    a.error->resize(ui::content_x, 104, metric_w, 96);
    a.energy->resize(ui::content_x + metric_w + 16, 104, metric_w, 96);
    a.terms->resize(ui::content_x + 2 * (metric_w + 16), 104,
                    content_w - 2 * (metric_w + 16), 96);
    int available = height - 212 - ui::margin - 16;
    int plot_h = available * 64 / 100;
    a.plot->resize(ui::content_x, 212, content_w, plot_h);
    a.inspector->resize(ui::content_x, 212 + plot_h + 16, content_w,
                        available - plot_h);
}

class StudioWindow : public Fl_Double_Window {
    App *app_;

public:
    StudioWindow()
        : Fl_Double_Window(ui::window_w, ui::window_h, "Fourier Studio"),
          app_(0)
    {
        color(ui::canvas);
        // All geometry is handled by layout(); do not also scale children.
        resizable(0);
        size_range(ui::min_w, ui::min_h);
    }
    void bind(App *a)
    {
        app_ = a;
        layout(*app_, w(), h());
    }
    void resize(int X, int Y, int W, int H)
    {
        Fl_Double_Window::resize(X, Y, W, H);
        if (app_)
            layout(*app_, W, H);
    }
};

static void build_amplitude(App &a)
{
    a.amplitude = new StudioSlider(268, "Amplitude", 0);
    a.amplitude->bounds(0.1, 5.0);
    a.amplitude->step(0.05);
    a.amplitude->value(1.0);
}

static void build_phase(App &a)
{
    a.phase = new StudioSlider(348, "Phase shift", 1);
    a.phase->bounds(-180, 180);
    a.phase->step(1);
    a.phase->value(0);
    a.phase->tooltip("Evaluate the waveform at x + phase. "
                     "Use arrow keys for precise changes.");
}

static void build_harmonics(App &a)
{
    a.harmonics = new StudioSlider(428, "Harmonics", 2);
    a.harmonics->bounds(1, 100);
    a.harmonics->step(1);
    a.harmonics->value(15);
    a.harmonics->tooltip("Include frequencies 1 through n. "
                         "Arrow keys change one harmonic at a time.");
}

static void build_sidebar_buttons(App &a)
{
    a.animate = new ActionButton(46, 602, 140, 44, "Animate", true);
    a.animate->callback(animate_cb, &a);
    a.animate->shortcut(' ');
    a.animate->tooltip("Build the signal one harmonic at a time. "
                       "Space starts or pauses the animation.");
    a.reset = new ActionButton(194, 602, 68, 44, "Reset", false);
    a.reset->callback(reset_cb, &a);
    a.reset->shortcut(FL_CTRL + 'r');
    a.reset->tooltip("Restore the original square wave settings. Ctrl+R.");
}

static void build_sidebar(App &a)
{
    a.header = new Header();
    a.sidebar = new Sidebar(&a.series);
    a.waveform = new WaveSelector();
    build_amplitude(a);
    build_phase(a);
    build_harmonics(a);
    a.samples = new SampleChoice();
    a.samples->tooltip("More samples improve the numerical "
                       "coefficient estimates.");
    a.waveform->callback(settings_cb, &a);
    a.amplitude->callback(settings_cb, &a);
    a.phase->callback(settings_cb, &a);
    a.harmonics->callback(settings_cb, &a);
    a.samples->callback(settings_cb, &a);
    build_sidebar_buttons(a);
    a.sidebar->end();
}

static void build_export(App &a)
{
    a.save = new ActionButton(0, 28, 136, 42, "Export CSV", false, true);
    a.save->callback(save_cb, &a);
    a.save->shortcut(FL_CTRL + 'e');
    a.save->tooltip("Export the current target, "
                    "reconstruction and error. Ctrl+E.");
}

static void build_metrics(App &a)
{
    a.error = new Metric("RMS ERROR");
    a.error->tooltip("Root mean square error, "
                     "measured at the sampled points.");
    a.energy = new Metric("ENERGY CAPTURED");
    a.energy->tooltip("Fraction of sampled signal energy "
                      "explained by the series, including its mean.");
    a.terms = new Metric("HARMONICS");
}

static void build_ui(App &a, StudioWindow &win)
{
    build_sidebar(a);
    build_export(a);
    build_metrics(a);
    a.plot = new WaveformPlot(&a.series);
    a.inspector = new Inspector(&a.series);
    win.end();
    win.callback(close_cb, &a);
    win.bind(&a);
    rebuild(&a);
}

#ifndef FOURIER_STUDIO_TEST
int main()
{
    Fl::set_font(FL_HELVETICA, " Inter");
    Fl::set_font(FL_HELVETICA_BOLD, "BInter");
    Fl::scheme("gtk+");
    Fl::background(246, 246, 249);
    Fl::background2(255, 255, 255);
    Fl::foreground(37, 40, 57);
    Fl::scrollbar_size(12);
    Fl_Tooltip::delay(0.55);
    Fl_Tooltip::color(ui::ink);
    Fl_Tooltip::textcolor(ui::paper);
    Fl_Tooltip::size(12);
    App a;
    StudioWindow win;
    build_ui(a, win);
    win.show();
    int result = Fl::run();
    Fl::remove_timeout(animation_tick, &a);
    return result;
}
#endif
