package space.animefu.starfallhaven;

import android.content.Context;
import android.graphics.*;
import android.view.*;
import java.io.*;
import java.util.*;

/** Touch-first procedural landing, neighboring settlement, trade, diplomacy, and family console. */
public final class RegionView extends View {
    public interface Host { void enterColony(GameWorld world); void save(GameWorld world,boolean explicit); }
    private static final int BG=Color.rgb(7,16,24),PANEL=Color.rgb(16,31,42),INK=Color.rgb(225,241,236),MUTED=Color.rgb(147,174,177),CYAN=Color.rgb(105,239,219),AMBER=Color.rgb(250,188,80);
    private final Paint p=new Paint(Paint.ANTI_ALIAS_FLAG),pixel=new Paint();private final Map<String,Bitmap> art=new HashMap<>();
    private final RectF mapRect=new RectF(),primary=new RectF(),aid=new RectF(),trade=new RectF(),family=new RectF();
    private final GameWorld world;private final Host host;private int safeLeft,safeTop,safeRight,safeBottom,selectedSettlement=-1;private float density=1;private String feedback="";
    public RegionView(Context context,GameWorld world,Host host){super(context);this.world=world;this.host=host;pixel.setFilterBitmap(false);load("MAP",AssetCatalog.REGION_MAP);load("FRIENDLY",AssetCatalog.SETTLEMENT_FRIENDLY);load("NEUTRAL",AssetCatalog.SETTLEMENT_NEUTRAL);load("HOSTILE",AssetCatalog.SETTLEMENT_HOSTILE);load("SKIFF",AssetCatalog.TRADE_SKIFF);setFocusable(true);}
    public GameWorld world(){return world;}
    @Override public WindowInsets onApplyWindowInsets(WindowInsets insets){if(android.os.Build.VERSION.SDK_INT>=30){android.graphics.Insets b=insets.getInsets(WindowInsets.Type.systemBars()|WindowInsets.Type.displayCutout());safeLeft=b.left;safeTop=b.top;safeRight=b.right;safeBottom=b.bottom;}else{safeLeft=insets.getSystemWindowInsetLeft();safeTop=insets.getSystemWindowInsetTop();safeRight=insets.getSystemWindowInsetRight();safeBottom=insets.getSystemWindowInsetBottom();}invalidate();return insets;}
    @Override protected void onSizeChanged(int w,int h,int ow,int oh){density=Math.min(getResources().getDisplayMetrics().density,Math.max(1.2f,(h-safeTop-safeBottom)/350f));}
    private float dp(float v){return v*density;}
    @Override protected void onDraw(Canvas c){super.onDraw(c);c.drawColor(BG);float left=safeLeft+dp(18),top=safeTop+dp(14),right=getWidth()-safeRight-dp(18),bottom=getHeight()-safeBottom-dp(14),panelW=Math.min(dp(360),right-left-dp(420));mapRect.set(left,top+dp(54),right-panelW-dp(18),bottom);drawHeader(c,left,top,right);drawMap(c);drawDetail(c,mapRect.right+dp(18),top+dp(54),right,bottom);}
    private void drawHeader(Canvas c,float l,float t,float r){text(c,world.landingSiteConfirmed?"REGIONAL FRONTIER":"CHOOSE A LANDING SITE",l,t+dp(29),dp(24),CYAN,true,Paint.Align.LEFT);text(c,"SEED "+world.worldSeed+"  •  "+world.regionalMap.validLandingSites().size()+" viable sites",r,t+dp(27),dp(13),MUTED,true,Paint.Align.RIGHT);}
    private void drawMap(Canvas c){p.setColor(PANEL);c.drawRoundRect(mapRect,dp(14),dp(14),p);Bitmap background=art.get("MAP");if(background!=null)c.drawBitmap(background,null,new RectF(mapRect.left+dp(8),mapRect.top+dp(8),mapRect.right-dp(8),mapRect.bottom-dp(8)),pixel);float cw=(mapRect.width()-dp(16))/world.regionalMap.width,ch=(mapRect.height()-dp(16))/world.regionalMap.height,ox=mapRect.left+dp(8),oy=mapRect.top+dp(8);
        for(RegionalMap.Cell cell:world.regionalMap.validLandingSites()){if(world.landingSiteConfirmed)break;int alpha=cell.x==world.selectedLandingX&&cell.y==world.selectedLandingY?210:45;p.setColor(Color.argb(alpha,105,239,219));c.drawRect(ox+cell.x*cw,oy+cell.y*ch,ox+(cell.x+1)*cw,oy+(cell.y+1)*ch,p);}
        if(world.landingSiteConfirmed&&world.factionSimulation!=null){List<FactionSimulation.Settlement> settlements=world.factionSimulation.settlements();for(int i=0;i<settlements.size();i++){FactionSimulation.Settlement s=settlements.get(i);FactionSimulation.Faction f=world.factionSimulation.faction(s.factionId);String key=f.relation()==FactionSimulation.Relation.FRIENDLY?"FRIENDLY":f.relation()==FactionSimulation.Relation.HOSTILE?"HOSTILE":"NEUTRAL";Bitmap icon=art.get(key);float x=ox+(s.x+.5f)*cw,y=oy+(s.y+.5f)*ch,size=dp(i==selectedSettlement?56:44);if(icon!=null)c.drawBitmap(icon,null,new RectF(x-size/2,y-size/2,x+size/2,y+size/2),pixel);p.setStyle(Paint.Style.STROKE);p.setStrokeWidth(dp(i==selectedSettlement?3:1));p.setColor(i==selectedSettlement?CYAN:Color.WHITE);c.drawCircle(x,y,size*.48f,p);p.setStyle(Paint.Style.FILL);}}
        float hx=ox+(world.selectedLandingX+.5f)*cw,hy=oy+(world.selectedLandingY+.5f)*ch;p.setColor(AMBER);c.drawCircle(hx,hy,dp(6),p);p.setStyle(Paint.Style.STROKE);p.setStrokeWidth(dp(2));c.drawCircle(hx,hy,dp(11),p);p.setStyle(Paint.Style.FILL);
    }
    private void drawDetail(Canvas c,float l,float t,float r,float b){p.setColor(PANEL);c.drawRoundRect(l,t,r,b,dp(14),dp(14),p);float x=l+dp(18),y=t+dp(28);if(!world.landingSiteConfirmed){RegionalMap.Cell site=world.selectedLandingSite();text(c,"PROPOSED HAVEN",x,y,dp(16),CYAN,true,Paint.Align.LEFT);text(c,pretty(site.biome.name()),x,y+dp(28),dp(21),INK,true,Paint.Align.LEFT);text(c,"Suitability  "+site.suitability+" / 100",x,y+dp(54),dp(14),AMBER,true,Paint.Align.LEFT);text(c,"Resources",x,y+dp(82),dp(12),MUTED,true,Paint.Align.LEFT);text(c,resources(site),x,y+dp(105),dp(14),INK,false,Paint.Align.LEFT);primary.set(l+dp(18),b-dp(66),r-dp(18),b-dp(16));button(c,primary,"LAND HERE",true);aid.setEmpty();trade.setEmpty();family.setEmpty();return;}
        List<FactionSimulation.Settlement> settlements=world.factionSimulation.settlements();if(selectedSettlement<0&& !settlements.isEmpty())selectedSettlement=0;FactionSimulation.Settlement s=settlements.get(Math.max(0,Math.min(selectedSettlement,settlements.size()-1)));FactionSimulation.Faction f=world.factionSimulation.faction(s.factionId);int relation=f.relation()==FactionSimulation.Relation.FRIENDLY?CYAN:f.relation()==FactionSimulation.Relation.HOSTILE?Color.rgb(255,102,112):AMBER;text(c,s.name,x,y,dp(21),INK,true,Paint.Align.LEFT);text(c,f.name,x,y+dp(25),dp(12),MUTED,false,Paint.Align.LEFT);text(c,f.relation().name()+"  "+f.standing,x,y+dp(52),dp(16),relation,true,Paint.Align.LEFT);text(c,"Population "+s.population+"  •  Prosperity "+s.prosperity,x,y+dp(68),dp(12),INK,false,Paint.Align.LEFT);text(c,"AI plan  "+pretty(s.lastStrategy.name()),x,y+dp(89),dp(12),AMBER,true,Paint.Align.LEFT);
        SocietySystems.Caravan caravan=caravanFor(f.id);if(caravan!=null&&!caravan.offers.isEmpty()){SocietySystems.TradeOffer offer=caravan.offers.get(0);Bitmap skiff=art.get("SKIFF");if(skiff!=null)c.drawBitmap(skiff,null,new RectF(r-dp(105),t+dp(14),r-dp(18),t+dp(76)),pixel);text(c,"Skiff: "+offer.resource+" ×"+offer.quantity+"  •  "+offer.unitPrice+" crystal",x,y+dp(112),dp(11),CYAN,true,Paint.Align.LEFT);}else text(c,"No trade skiff in range",x,y+dp(112),dp(11),MUTED,false,Paint.Align.LEFT);
        int dependents=0;for(SocietySystems.Person person:world.society.families.people)if(person.stage!=SocietySystems.AgeStage.ADULT)dependents++;text(c,"Households "+households()+"  •  Children "+dependents+"  •  Expected "+world.society.families.pregnancies.size(),x,y+dp(116),dp(9),INK,false,Paint.Align.LEFT);if(!feedback.isEmpty())text(c,feedback,r-dp(18),y+dp(116),dp(9),AMBER,true,Paint.Align.RIGHT);
        float by=b-dp(118),gap=dp(8),bw=(r-l-dp(52))/3;aid.set(l+dp(18),by,l+dp(18)+bw,by+dp(48));trade.set(aid.right+gap,by,aid.right+gap+bw,by+dp(48));family.set(trade.right+gap,by,trade.right+gap+bw,by+dp(48));button(c,aid,"SEND AID",false);button(c,trade,"BUY 1",caravan!=null);button(c,family,"PLAN CHILD",true);primary.set(l+dp(18),b-dp(58),r-dp(18),b-dp(12));button(c,primary,"RETURN TO HAVEN",true);
    }
    private SocietySystems.Caravan caravanFor(String factionId){for(SocietySystems.Caravan c:world.society.caravans)if(c.factionId.equals(factionId)&&world.day>=c.arrivalDay&&world.day<=c.departureDay)return c;return null;}
    private int households(){Set<String> ids=new HashSet<>();for(SocietySystems.Person p:world.society.families.people)if(p.householdId!=null)ids.add(p.householdId);return ids.size();}
    @Override public boolean onTouchEvent(MotionEvent e){if(e.getActionMasked()!=MotionEvent.ACTION_UP)return true;float x=e.getX(),y=e.getY();if(primary.contains(x,y)){if(!world.landingSiteConfirmed){if(world.confirmLandingSite()){world.initializeSociety(world.worldSeed);host.save(world,false);host.enterColony(world);}}else host.enterColony(world);performClick();return true;}if(!world.landingSiteConfirmed&&mapRect.contains(x,y)){int[] cell=cellAt(x,y);world.selectLandingSite(cell[0],cell[1]);invalidate();performClick();return true;}if(world.landingSiteConfirmed&&mapRect.contains(x,y)){selectedSettlement=nearestSettlement(x,y);feedback="";invalidate();performClick();return true;}if(selectedSettlement>=0){FactionSimulation.Settlement s=world.factionSimulation.settlements().get(selectedSettlement);if(aid.contains(x,y)){feedback=world.offerAid(s.factionId)?"Aid delivered":"Need 5 food";host.save(world,false);invalidate();}else if(trade.contains(x,y)){SocietySystems.Caravan caravan=caravanFor(s.factionId);SocietySystems.TradeReceipt receipt=caravan==null?null:world.buyTrade(caravan.id,0,1);feedback=receipt!=null&&receipt.accepted?"Trade complete":receipt==null?"No skiff":receipt.reason;host.save(world,false);invalidate();}else if(family.contains(x,y)&&world.colonists.size()>=2){SocietySystems.FamilyResult result=world.planChild(world.colonists.get(0).id,world.colonists.get(1).id);feedback=result.accepted?"Child expected":result.reason;host.save(world,false);invalidate();}}performClick();return true;}
    @Override public boolean performClick(){super.performClick();return true;}
    private int[] cellAt(float x,float y){float ox=mapRect.left+dp(8),oy=mapRect.top+dp(8),cw=(mapRect.width()-dp(16))/world.regionalMap.width,ch=(mapRect.height()-dp(16))/world.regionalMap.height;return new int[]{Math.max(0,Math.min(world.regionalMap.width-1,(int)((x-ox)/cw))),Math.max(0,Math.min(world.regionalMap.height-1,(int)((y-oy)/ch)))};}
    private int nearestSettlement(float x,float y){int[] cell=cellAt(x,y);int best=-1,dist=Integer.MAX_VALUE;List<FactionSimulation.Settlement> all=world.factionSimulation.settlements();for(int i=0;i<all.size();i++){FactionSimulation.Settlement s=all.get(i);int d=Math.abs(s.x-cell[0])+Math.abs(s.y-cell[1]);if(d<dist){dist=d;best=i;}}return best;}
    private String resources(RegionalMap.Cell c){StringBuilder out=new StringBuilder();for(RegionalMap.Resource r:c.resources){if(out.length()>0)out.append(" • ");out.append(pretty(r.name()));}return out.toString();}
    private String pretty(String s){return s.toLowerCase(Locale.US).replace('_',' ');}
    private void button(Canvas c,RectF r,String label,boolean active){p.setColor(active?Color.rgb(34,117,112):Color.rgb(28,53,65));c.drawRoundRect(r,dp(9),dp(9),p);p.setStyle(Paint.Style.STROKE);p.setStrokeWidth(dp(2));p.setColor(active?CYAN:Color.rgb(74,105,112));c.drawRoundRect(r,dp(9),dp(9),p);p.setStyle(Paint.Style.FILL);text(c,label,r.centerX(),r.centerY()+dp(5),dp(13),INK,true,Paint.Align.CENTER);}
    private void text(Canvas c,String s,float x,float y,float size,int color,boolean bold,Paint.Align align){p.setTextSize(size);p.setColor(color);p.setTypeface(bold?Typeface.DEFAULT_BOLD:Typeface.DEFAULT);p.setTextAlign(align);c.drawText(s,x,y,p);}
    private void load(String key,String path){try(InputStream in=getContext().getAssets().open(path)){Bitmap b=BitmapFactory.decodeStream(in);if(b!=null){b.setDensity(Bitmap.DENSITY_NONE);art.put(key,b);}}catch(IOException ignored){}}
}
