package thb.jeanluc.adventure.io;

import thb.jeanluc.adventure.io.text.QuestText;
import thb.jeanluc.adventure.io.text.QuestView;
import thb.jeanluc.adventure.io.text.Span;
import thb.jeanluc.adventure.io.text.Style;

import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import java.awt.Color;
import java.awt.Font;
import java.awt.Insets;

/** Read-only styled view of the quest log, shown under the map. */
public class QuestPanel extends JTextPane {

    public QuestPanel(Font font) {
        setEditable(false);
        setBackground(new Color(0x0b, 0x0e, 0x13));
        setForeground(new Color(0xcf, 0xd6, 0xe0));
        setFont(font.deriveFont(12f));
        setMargin(new Insets(8, 10, 8, 10));
    }

    public void show(QuestView view) {
        SwingUtilities.invokeLater(() -> {
            StyledDocument doc = getStyledDocument();
            try {
                doc.remove(0, doc.getLength());
                for (Span sp : QuestText.render(view).spans()) {
                    SimpleAttributeSet as = new SimpleAttributeSet();
                    StyleConstants.setForeground(as, colorFor(sp.style()));
                    if (sp.style() == Style.HEADING) {
                        StyleConstants.setBold(as, true);
                    }
                    doc.insertString(doc.getLength(), sp.text(), as);
                }
                setCaretPosition(0);
            } catch (BadLocationException ignored) {
                // replace-only; cannot occur with getLength()
            }
        });
    }

    private Color colorFor(Style s) {
        return switch (s) {
            case HEADING -> new Color(0xc9, 0x8a, 0xe0);
            case ITEM -> new Color(0x46, 0xc8, 0xd8);
            case NPC -> new Color(0xe6, 0xc3, 0x4a);
            case EXIT -> new Color(0x6f, 0xcf, 0x73);
            case DANGER -> new Color(0xe0, 0x6c, 0x6c);
            case DIM -> new Color(0x6b, 0x72, 0x80);
            case PLAIN -> new Color(0xcf, 0xd6, 0xe0);
        };
    }
}
