"""Panel backgrounds and semantic editing groups for the quantitative figures."""
from matplotlib.axes import Axes
from matplotlib.legend import Legend
from matplotlib.patches import FancyBboxPatch
from matplotlib.text import Text
from matplotlib.transforms import Affine2D

INK, MUTED, PINK, INDIGO = '#192638', '#4f5c71', '#c72c6a', '#5363a7'
PALE, BORDER = '#f5f6fa', '#d9dee9'

# Bounds of the molecular comparisons that share a shaded field, in paper mm.
FIELDS = {
    '06': [(0.4,0.5,179.2,83.8)],
    'S2': [(0.4,0.4,179.2,46.3)],
    'S1': [(0.4,0.4,179.2,48.3)]
}

def add_surface(plate, x, y, width, height, fill, z):
    transform=Affine2D().scale(1/plate.w,-1/plate.h).translate(0,1)+plate.f.transFigure
    patch=FancyBboxPatch((x,y),width,height,boxstyle='round,pad=0,rounding_size=1.2',
                         facecolor=fill,edgecolor=BORDER,linewidth=.55,zorder=z,transform=transform)
    plate.f.add_artist(patch)
    return patch


def scientific_layers(plate, name):
    ident=name.split('_')[0]
    layers={}
    def identify(artist, path):
        key=f'edit-{len(layers)}'
        artist.set_gid(key)
        layers[key]=path

    for dims in FIELDS.get(ident,[]):
        identify(add_surface(plate,*dims,PALE,-5),('Comparison background',))
    for x,y,letter,title,headings in plate.panels:
        panel=f'{letter} · {title}'
        right=min([xx for xx,yy,*_ in plate.panels if abs(yy-y)<.5 and xx>x] + [plate.w+1])
        in_field=any(l<=x<l+w and t<=y<t+h for l,t,w,h in FIELDS.get(ident,[]))
        if not in_field:
            band=add_surface(plate,x-.55,y-2.65,right-x-1.15,5.6,PALE,-4)
            identify(band,(panel,'Heading'))
        for a in headings:identify(a,(panel,'Heading'))
    plate.f.canvas.draw()
    renderer=plate.f.canvas.get_renderer()
    w,h=plate.f.bbox.size
    for a in [*plate.f.axes,*plate.f.artists,*plate.f.texts,*plate.f.patches,*plate.f.legends,*plate.f.lines]:
        if a.get_gid() in layers:continue
        if isinstance(a,Text):
            fracx,fracy=a.get_position()
            x,y=fracx*plate.w,(1-fracy)*plate.h
        else:
            bounds=a.get_window_extent(renderer)
            x=(bounds.x0+bounds.width/2)*plate.w/w
            y=(1-(bounds.y0+bounds.height/2)/h)*plate.h
        choices=[p for p in plate.panels if p[0]<=x+1.8 and p[1]<=y+1.5]
        px,py,letter,title,_=max(choices or plate.panels[:1],key=lambda p:(p[1],p[0]))
        panel=f'{letter} · {title}'
        path=[panel]
        if ident=='03' and y>72:path=['Iodine forecast']
        if ident=='06' and letter=='d' and 159<y:
            path.append('Narrow linewidth' if x<90 else 'Broad linewidth')
        if ident=='06' and letter=='a' and 6<y<84:
            path.append(['para-I','Parent','para-Cl'][min(2,int(x//60))])
        if ident=='S2':
            if letter=='a' and 14<y<46:
                path.append('Complete para-I cation' if x<44 else
                            ['Parent ring','Fluorinated ring','Chlorinated ring','Brominated ring','Iodinated ring'][max(0,min(4,int((x-49)//26)))])
            if letter=='b' and 55<y<89:
                path.append(['Parent dmit','dmid','C₃S₅ isomer','C₅H₆S₄'][min(3,int(x//45))])
        if ident=='04' and letter=='b' and 7<y<58:path.append('Parent' if x<125 else 'para-I')
        if isinstance(a,Axes):
            label='Molecular view' if a.images and not a.axison else 'Plot'
            if ident=='03' and letter in ('a','b'):label='Crystal contact' if y<45 else 'Side-on ligand fold'
            if ident=='06' and letter=='a':label='Calculation cell' if y<61 else 'Enlarged anion'
            if ident=='S6' and y<133:
                from make_figures import NAMES
                label=list(NAMES.values())[min(16,plate.f.axes.index(a)//2)]
            if a.axison:a.set_facecolor('none')
            path.append(label)
            for line in a.lines:
                caption=line.get_label()
                if caption and not caption.startswith('_'):line.set_gid(caption)
        elif isinstance(a,Legend):path.append('Legend')
        elif isinstance(a,Text):path.append('Labels')
        else:path.append('Marks and guides')
        identify(a,tuple(path))
    return layers
