package com.okithaki.autoapp;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.provider.Settings;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * V249530 professional manual Neighborhood UI.
 * Mode A: same Wi-Fi cell where every phone is a tiny encrypted text server.
 * Mode B: existing Nearby Connections radar. Both are isolated from MainActivity.
 */
public final class EmergencyNeighborhoodActivity extends Activity implements EmergencyNeighborhoodService.Listener, NeighborhoodCellService.Listener {
    private static final int PERMISSION_REQUEST=249530;
    private static final String MODE_CELL="cell";
    private static final String MODE_NEARBY="nearby";
    private final Handler handler=new Handler(Looper.getMainLooper());
    private final SecureRandom random=new SecureRandom();

    private EmergencyNeighborhoodService nearbyService;
    private NeighborhoodCellService cellService;
    private boolean nearbyBound=false,cellBound=false;
    private String selectedMode=MODE_CELL;
    private String nickname="Μέλος";

    private Button cellModeButton,nearbyModeButton,startButton;
    private LinearLayout cellCodeBox;
    private EditText cellCodeInput,composer;
    private TextView modeHelp,statusView,peersView,safetyView;
    private LinearLayout messagesBox;
    private ScrollView messagesScroll;

    private final Runnable refreshRunnable=new Runnable(){@Override public void run(){refreshUi();handler.postDelayed(this,1400L);}};

    private final ServiceConnection nearbyConnection=new ServiceConnection(){
        public void onServiceConnected(ComponentName n,IBinder b){nearbyService=((EmergencyNeighborhoodService.LocalBinder)b).getService();nearbyService.addListener(EmergencyNeighborhoodActivity.this);nearbyBound=true;refreshUi();}
        public void onServiceDisconnected(ComponentName n){if(nearbyService!=null)nearbyService.removeListener(EmergencyNeighborhoodActivity.this);nearbyService=null;nearbyBound=false;refreshUi();}
    };
    private final ServiceConnection cellConnection=new ServiceConnection(){
        public void onServiceConnected(ComponentName n,IBinder b){cellService=((NeighborhoodCellService.LocalBinder)b).getService();cellService.addListener(EmergencyNeighborhoodActivity.this);cellBound=true;refreshUi();}
        public void onServiceDisconnected(ComponentName n){if(cellService!=null)cellService.removeListener(EmergencyNeighborhoodActivity.this);cellService=null;cellBound=false;refreshUi();}
    };

    @Override protected void onCreate(Bundle state){
        super.onCreate(state);
        nickname=getSharedPreferences("ok_ithaki_prefs",MODE_PRIVATE).getString("nickname","Μέλος");
        selectedMode=getSharedPreferences("ok_ithaki_neighborhood_ui_v249530",MODE_PRIVATE).getString("mode",MODE_CELL);
        buildUi();setSelectedMode(selectedMode,false);requestPermissionsForSelectedMode();
    }
    @Override protected void onStart(){
        super.onStart();
        bindService(new Intent(this,EmergencyNeighborhoodService.class),nearbyConnection,Context.BIND_AUTO_CREATE);
        bindService(new Intent(this,NeighborhoodCellService.class),cellConnection,Context.BIND_AUTO_CREATE);
        handler.post(refreshRunnable);
    }
    @Override protected void onStop(){
        handler.removeCallbacks(refreshRunnable);
        if(nearbyBound){try{if(nearbyService!=null)nearbyService.removeListener(this);}catch(Exception ignored){}try{unbindService(nearbyConnection);}catch(Exception ignored){}}
        if(cellBound){try{if(cellService!=null)cellService.removeListener(this);}catch(Exception ignored){}try{unbindService(cellConnection);}catch(Exception ignored){}}
        nearbyBound=false;cellBound=false;nearbyService=null;cellService=null;super.onStop();
    }
    @Override public void onNeighborhoodChanged(){runOnUiThread(this::refreshUi);}
    @Override public void onCellChanged(){runOnUiThread(this::refreshUi);}

    private void buildUi(){
        getWindow().setStatusBarColor(Color.rgb(3,10,18));
        LinearLayout root=new LinearLayout(this);root.setOrientation(LinearLayout.VERTICAL);root.setPadding(dp(12),dp(10),dp(12),dp(10));root.setBackgroundColor(Color.rgb(3,10,18));

        LinearLayout top=row();Button close=button("‹ Πίσω");close.setOnClickListener(v->finish());TextView title=label("🛜 Γειτονιά & Ραντάρ",21,true);title.setGravity(Gravity.CENTER);
        top.addView(close,new LinearLayout.LayoutParams(dp(90),dp(46)));top.addView(title,new LinearLayout.LayoutParams(0,dp(46),1f));root.addView(top);

        safetyView=label("Χειροκίνητη λειτουργία μόνο. Η κανονική σύνδεση της OK ITHAKI δεν αλλάζει. Σε σφάλμα σταματά μόνο η Γειτονιά και εμφανίζεται ειδοποίηση ασφαλούς επιστροφής.",13,false);
        safetyView.setTextColor(Color.rgb(255,226,154));safetyView.setPadding(dp(12),dp(10),dp(12),dp(10));safetyView.setBackgroundColor(Color.rgb(42,35,18));root.addView(safetyView);

        LinearLayout modes=row();cellModeButton=button("🛜 Κυψέλη Wi‑Fi");nearbyModeButton=button("📡 Nearby Ραντάρ");
        cellModeButton.setOnClickListener(v->setSelectedMode(MODE_CELL,true));nearbyModeButton.setOnClickListener(v->setSelectedMode(MODE_NEARBY,true));modes.addView(cellModeButton,weightedButtonLp(58));modes.addView(nearbyModeButton,weightedButtonLp(58));root.addView(modes);

        modeHelp=label("",13,false);modeHelp.setPadding(dp(10),dp(7),dp(10),dp(7));modeHelp.setTextColor(Color.rgb(177,221,244));root.addView(modeHelp);

        cellCodeBox=row();cellCodeInput=new EditText(this);cellCodeInput.setSingleLine(true);cellCodeInput.setTextColor(Color.WHITE);cellCodeInput.setHintTextColor(Color.GRAY);cellCodeInput.setHint("Κοινός κωδικός Κυψέλης · 8 χαρακτήρες");cellCodeInput.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);cellCodeInput.setBackgroundColor(Color.rgb(18,34,48));cellCodeInput.setPadding(dp(12),dp(9),dp(12),dp(9));
        String savedCode=getSharedPreferences("ok_ithaki_neighborhood_ui_v249530",MODE_PRIVATE).getString("cell_code","");if(savedCode.isEmpty())savedCode=generateCellCode();cellCodeInput.setText(savedCode);
        Button newCode=button("Νέος κωδικός");newCode.setOnClickListener(v->{String c=generateCellCode();cellCodeInput.setText(c);saveCellCode(c);Toast.makeText(this,"Βάλε τον ίδιο κωδικό σε όλα τα κινητά της Κυψέλης.",Toast.LENGTH_LONG).show();});
        cellCodeBox.addView(cellCodeInput,new LinearLayout.LayoutParams(0,dp(50),1f));cellCodeBox.addView(newCode,new LinearLayout.LayoutParams(dp(120),dp(50)));root.addView(cellCodeBox);

        LinearLayout controls=row();startButton=button("▶ Χειροκίνητη έναρξη");Button stop=button("■ Διακοπή");Button radar=button("⌁ Ανανέωση Ραντάρ");controls.addView(startButton,weightedButtonLp(54));controls.addView(stop,weightedButtonLp(54));controls.addView(radar,weightedButtonLp(54));root.addView(controls);
        startButton.setOnClickListener(v->startSelected());stop.setOnClickListener(v->stopSelected());radar.setOnClickListener(v->restartSelectedRadar());

        LinearLayout network=row();Button wifi=button("🛜 Ρυθμίσεις Wi‑Fi");Button hotspot=button("📶 Ρυθμίσεις Hotspot");Button clear=button("🗑 Καθαρισμός");network.addView(wifi,weightedButtonLp(48));network.addView(hotspot,weightedButtonLp(48));network.addView(clear,weightedButtonLp(48));root.addView(network);
        wifi.setOnClickListener(v->safeStartSettings(Settings.ACTION_WIFI_SETTINGS));hotspot.setOnClickListener(v->openHotspotSettings());clear.setOnClickListener(v->clearSelected());

        statusView=label("Κατάσταση: ανενεργή",13,true);statusView.setTextColor(Color.rgb(117,231,190));statusView.setPadding(dp(9),dp(8),dp(9),dp(5));root.addView(statusView);
        peersView=label("Κοντινά κινητά: 0",12,false);peersView.setTextColor(Color.LTGRAY);peersView.setPadding(dp(9),dp(1),dp(9),dp(7));root.addView(peersView);

        messagesScroll=new ScrollView(this);messagesScroll.setFillViewport(true);messagesBox=new LinearLayout(this);messagesBox.setOrientation(LinearLayout.VERTICAL);messagesBox.setPadding(dp(4),dp(4),dp(4),dp(8));messagesScroll.addView(messagesBox,new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));root.addView(messagesScroll,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,0,1f));

        LinearLayout quick=row();for(String q:new String[]{"❤️","🤝","🙏","🆘 SOS"}){Button b=button(q);b.setOnClickListener(v->{String value=((Button)v).getText().toString();sendText(value,value.contains("SOS")?"sos":"text");});quick.addView(b,weightedButtonLp(46));}root.addView(quick);

        LinearLayout compose=row();composer=new EditText(this);composer.setHint("Γράψε μόνο κείμενο…");composer.setHintTextColor(Color.GRAY);composer.setTextColor(Color.WHITE);composer.setTextSize(16f);composer.setSingleLine(false);composer.setMaxLines(4);composer.setPadding(dp(12),dp(10),dp(12),dp(10));composer.setBackgroundColor(Color.rgb(18,33,48));Button send=button("Αποστολή");send.setOnClickListener(v->{String t=composer.getText().toString();if(sendText(t,"text"))composer.setText("");});compose.addView(composer,new LinearLayout.LayoutParams(0,ViewGroup.LayoutParams.WRAP_CONTENT,1f));compose.addView(send,new LinearLayout.LayoutParams(dp(108),ViewGroup.LayoutParams.MATCH_PARENT));root.addView(compose);

        TextView footer=label("Μόνο γραπτά μηνύματα και SOS · χωρίς φωτογραφίες, αρχεία, μικρόφωνο ή κάμερα · V249530",11,false);footer.setTextColor(Color.GRAY);footer.setGravity(Gravity.CENTER);footer.setPadding(4,8,4,2);root.addView(footer);
        setContentView(root);
    }

    private void setSelectedMode(String mode,boolean announce){
        selectedMode=MODE_NEARBY.equals(mode)?MODE_NEARBY:MODE_CELL;getSharedPreferences("ok_ithaki_neighborhood_ui_v249530",MODE_PRIVATE).edit().putString("mode",selectedMode).apply();
        boolean cell=MODE_CELL.equals(selectedMode);cellCodeBox.setVisibility(cell?View.VISIBLE:View.GONE);
        cellModeButton.setBackgroundColor(cell?Color.rgb(9,109,83):Color.rgb(26,55,78));nearbyModeButton.setBackgroundColor(cell?Color.rgb(26,55,78):Color.rgb(9,109,83));
        modeHelp.setText(cell?"Κάθε κινητό γίνεται μικροserver. Όλα τα κινητά πρέπει να είναι στο ίδιο Wi‑Fi ή hotspot και να έχουν τον ίδιο κωδικό Κυψέλης. Ανακάλυψη με NSD και εφεδρικό UDP Ραντάρ.":"Άμεση κοντινή σύνδεση με Google Nearby μέσω Bluetooth/BLE/Wi‑Fi. Ξεκινά μόνο με δικό σου πάτημα και σταματά χειροκίνητα.");
        if(announce){requestPermissionsForSelectedMode();refreshUi();}
    }

    private void startSelected(){
        if(!hasPermissionsForSelectedMode()){requestPermissionsForSelectedMode();Toast.makeText(this,"Δώσε πρώτα τις απαιτούμενες άδειες.",Toast.LENGTH_LONG).show();return;}
        if(MODE_CELL.equals(selectedMode)){
            String code=cellCodeInput.getText().toString().trim();if(code.length()<8){Toast.makeText(this,"Ο κωδικός Κυψέλης χρειάζεται τουλάχιστον 8 χαρακτήρες.",Toast.LENGTH_LONG).show();return;}saveCellCode(code);
            if(nearbyService!=null)nearbyService.stopNeighborhood();
            Intent i=new Intent(this,NeighborhoodCellService.class).setAction(NeighborhoodCellService.ACTION_START).putExtra(NeighborhoodCellService.EXTRA_NICKNAME,nickname).putExtra(NeighborhoodCellService.EXTRA_CELL_CODE,code);startForegroundSafely(i,"Κυψέλη");
        }else{
            if(cellService!=null)cellService.stopCell();
            Intent i=new Intent(this,EmergencyNeighborhoodService.class).setAction(EmergencyNeighborhoodService.ACTION_START).putExtra(EmergencyNeighborhoodService.EXTRA_NICKNAME,nickname);startForegroundSafely(i,"Nearby Ραντάρ");
        }
    }

    private void startForegroundSafely(Intent i,String label){try{if(Build.VERSION.SDK_INT>=26)startForegroundService(i);else startService(i);}catch(Exception e){Toast.makeText(this,"Δεν ξεκίνησε το "+label+": "+e.getMessage(),Toast.LENGTH_LONG).show();}}
    private void stopSelected(){if(MODE_CELL.equals(selectedMode)){if(cellService!=null)cellService.stopCell();else stopService(new Intent(this,NeighborhoodCellService.class));}else{if(nearbyService!=null)nearbyService.stopNeighborhood();else stopService(new Intent(this,EmergencyNeighborhoodService.class));}}
    private void restartSelectedRadar(){if(MODE_CELL.equals(selectedMode)){if(cellService!=null)cellService.restartRadar();else Toast.makeText(this,"Πάτησε πρώτα έναρξη Κυψέλης.",Toast.LENGTH_SHORT).show();}else{if(nearbyService!=null)nearbyService.restartDiscovery();else Toast.makeText(this,"Πάτησε πρώτα έναρξη Nearby.",Toast.LENGTH_SHORT).show();}}
    private void clearSelected(){if(MODE_CELL.equals(selectedMode)){if(cellService!=null)cellService.clearMessages();}else if(nearbyService!=null)nearbyService.clearMessages();}

    private boolean sendText(String text,String kind){
        String clean=text==null?"":text.trim();if(clean.isEmpty())return false;
        try{
            String raw;
            if(MODE_CELL.equals(selectedMode)){if(cellService==null){Toast.makeText(this,"Πάτησε πρώτα χειροκίνητη έναρξη Κυψέλης.",Toast.LENGTH_SHORT).show();return false;}raw=cellService.sendMessage(clean,nickname,kind);}
            else{if(nearbyService==null){Toast.makeText(this,"Πάτησε πρώτα χειροκίνητη έναρξη Nearby.",Toast.LENGTH_SHORT).show();return false;}raw=nearbyService.sendMessage(("sos".equals(kind)?"🆘 ":"")+clean,nickname);}
            JSONObject r=new JSONObject(raw);if(!r.optBoolean("ok",false)){String reason=r.optString("message",r.optString("reason","σφάλμα"));Toast.makeText(this,"Δεν στάλθηκε: "+reason,Toast.LENGTH_LONG).show();return false;}int targets=r.optInt("targets",0);if(MODE_CELL.equals(selectedMode)&&targets>0)Toast.makeText(this,"Το μήνυμα μπήκε σε αποστολή προς "+targets+" κινητό"+(targets==1?"":"ά")+".",Toast.LENGTH_SHORT).show();return true;
        }catch(Exception e){Toast.makeText(this,"Δεν στάλθηκε: "+e.getMessage(),Toast.LENGTH_LONG).show();return false;}
    }

    private void refreshUi(){
        if(statusView==null)return;
        try{
            String statusRaw,peersRaw,messagesRaw;
            if(MODE_CELL.equals(selectedMode)){
                if(cellService==null){showInactive("Κυψέλη Wi‑Fi");return;}statusRaw=cellService.getStatusJson();peersRaw=cellService.getPeersJson();messagesRaw=cellService.getMessagesJson();
            }else{
                if(nearbyService==null){showInactive("Nearby Ραντάρ");return;}statusRaw=nearbyService.getStatusJson();peersRaw=nearbyService.getPeersJson();messagesRaw=nearbyService.getMessagesJson();
            }
            JSONObject s=new JSONObject(statusRaw);boolean running=s.optBoolean("running",false);String error=s.optString("last_error","");
            String transport=MODE_CELL.equals(selectedMode)?"Κυψέλη Wi‑Fi / μικροserver":"Nearby P2P Ραντάρ";
            statusView.setText("Κατάσταση: "+(running?"ΕΝΕΡΓΗ":"ανενεργή")+" · "+transport+" · κινητά "+s.optInt("connected",0)+(MODE_CELL.equals(selectedMode)&&s.optInt("port",0)>0?" · θύρα "+s.optInt("port"):"")+(error.isEmpty()?"":"\nΕνημέρωση: "+error));
            startButton.setEnabled(!running);renderPeers(new JSONArray(peersRaw));renderMessages(new JSONArray(messagesRaw));
        }catch(Exception e){statusView.setText("Κατάσταση: σφάλμα προβολής · "+e.getMessage());}
    }
    private void showInactive(String mode){statusView.setText("Κατάσταση: "+mode+" δεν έχει ξεκινήσει.");peersView.setText("Κοντινά κινητά: 0");startButton.setEnabled(true);renderMessages(new JSONArray());}

    private void renderPeers(JSONArray peers){StringBuilder b=new StringBuilder("Κοντινά κινητά: ").append(peers.length());for(int i=0;i<peers.length();i++){JSONObject p=peers.optJSONObject(i);if(p==null)continue;b.append("\n● ").append(p.optString("name","Κινητό"));String source=p.optString("source","");if(!source.isEmpty())b.append(" · ").append(source);if(p.optInt("port",0)>0)b.append(" · ").append(p.optString("host","")).append(":").append(p.optInt("port"));}peersView.setText(b.toString());}

    private void renderMessages(JSONArray rows){
        messagesBox.removeAllViews();if(rows.length()==0){TextView empty=label("Δεν υπάρχουν μηνύματα. Επίλεξε λειτουργία και πάτησε χειροκίνητη έναρξη στα κινητά.",14,false);empty.setTextColor(Color.GRAY);empty.setGravity(Gravity.CENTER);empty.setPadding(dp(12),dp(40),dp(12),dp(40));messagesBox.addView(empty);return;}
        for(int i=0;i<rows.length();i++){JSONObject row=rows.optJSONObject(i);if(row==null)continue;boolean own=row.optBoolean("own",false),sos="sos".equals(row.optString("kind"));TextView bubble=label("",15,false);String who=own?"Εγώ":row.optString("nickname","Κοντινό μέλος");String time=formatTime(row.optLong("created_at",0));bubble.setText((sos?"🆘 ":"")+who+(time.isEmpty()?"":" · "+time)+"\n"+row.optString("text",""));bubble.setTextColor(Color.WHITE);bubble.setBackgroundColor(sos?Color.rgb(113,31,34):(own?Color.rgb(20,86,72):Color.rgb(25,43,64)));bubble.setPadding(dp(12),dp(9),dp(12),dp(9));LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams((int)(getResources().getDisplayMetrics().widthPixels*.84),ViewGroup.LayoutParams.WRAP_CONTENT);lp.gravity=own?Gravity.END:Gravity.START;lp.setMargins(dp(4),dp(4),dp(4),dp(4));messagesBox.addView(bubble,lp);}
        messagesScroll.post(()->messagesScroll.fullScroll(View.FOCUS_DOWN));
    }

    private void requestPermissionsForSelectedMode(){
        List<String> p=new ArrayList<String>();
        if(Build.VERSION.SDK_INT>=33){if(checkSelfPermission(Manifest.permission.NEARBY_WIFI_DEVICES)!=PackageManager.PERMISSION_GRANTED)p.add(Manifest.permission.NEARBY_WIFI_DEVICES);if(checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)!=PackageManager.PERMISSION_GRANTED)p.add(Manifest.permission.POST_NOTIFICATIONS);}
        if(MODE_NEARBY.equals(selectedMode)){
            if(Build.VERSION.SDK_INT<=28&&checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED)p.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            else if(Build.VERSION.SDK_INT>=29&&Build.VERSION.SDK_INT<=32&&checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED)p.add(Manifest.permission.ACCESS_FINE_LOCATION);
            if(Build.VERSION.SDK_INT>=31){if(checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN)!=PackageManager.PERMISSION_GRANTED)p.add(Manifest.permission.BLUETOOTH_SCAN);if(checkSelfPermission(Manifest.permission.BLUETOOTH_ADVERTISE)!=PackageManager.PERMISSION_GRANTED)p.add(Manifest.permission.BLUETOOTH_ADVERTISE);if(checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT)!=PackageManager.PERMISSION_GRANTED)p.add(Manifest.permission.BLUETOOTH_CONNECT);}
        }
        if(!p.isEmpty())requestPermissions(p.toArray(new String[0]),PERMISSION_REQUEST);
    }
    private boolean hasPermissionsForSelectedMode(){
        if(Build.VERSION.SDK_INT>=33&&checkSelfPermission(Manifest.permission.NEARBY_WIFI_DEVICES)!=PackageManager.PERMISSION_GRANTED)return false;
        if(MODE_CELL.equals(selectedMode))return true;
        if(Build.VERSION.SDK_INT<=28&&checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED)return false;
        if(Build.VERSION.SDK_INT>=29&&Build.VERSION.SDK_INT<=32&&checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED)return false;
        if(Build.VERSION.SDK_INT>=31&&(checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN)!=PackageManager.PERMISSION_GRANTED||checkSelfPermission(Manifest.permission.BLUETOOTH_ADVERTISE)!=PackageManager.PERMISSION_GRANTED||checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT)!=PackageManager.PERMISSION_GRANTED))return false;return true;
    }

    private void saveCellCode(String code){getSharedPreferences("ok_ithaki_neighborhood_ui_v249530",MODE_PRIVATE).edit().putString("cell_code",code).apply();}
    private String generateCellCode(){String alphabet="ABCDEFGHJKLMNPQRSTUVWXYZ23456789";StringBuilder b=new StringBuilder();for(int i=0;i<8;i++)b.append(alphabet.charAt(random.nextInt(alphabet.length())));return b.toString();}
    private void safeStartSettings(String action){try{startActivity(new Intent(action));}catch(Exception e){Toast.makeText(this,"Δεν άνοιξαν οι ρυθμίσεις.",Toast.LENGTH_SHORT).show();}}
    private void openHotspotSettings(){for(String action:new String[]{"android.settings.WIFI_TETHER_SETTINGS",Settings.ACTION_WIRELESS_SETTINGS,Settings.ACTION_WIFI_SETTINGS})try{startActivity(new Intent(action));return;}catch(Exception ignored){}}
    private LinearLayout row(){LinearLayout l=new LinearLayout(this);l.setOrientation(LinearLayout.HORIZONTAL);l.setGravity(Gravity.CENTER_VERTICAL);l.setPadding(0,dp(3),0,dp(3));return l;}
    private Button button(String text){Button b=new Button(this);b.setText(text);b.setTextColor(Color.WHITE);b.setTextSize(12f);b.setAllCaps(false);b.setPadding(dp(4),dp(4),dp(4),dp(4));b.setBackgroundColor(Color.rgb(26,55,78));return b;}
    private TextView label(String text,int size,boolean bold){TextView t=new TextView(this);t.setText(text);t.setTextColor(Color.WHITE);t.setTextSize(size);if(bold)t.setTypeface(Typeface.DEFAULT_BOLD);return t;}
    private LinearLayout.LayoutParams weightedButtonLp(int height){LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(0,dp(height),1f);lp.setMargins(dp(2),dp(2),dp(2),dp(2));return lp;}
    private int dp(int v){return Math.round(v*getResources().getDisplayMetrics().density);}
    private String formatTime(long seconds){if(seconds<=0)return"";return new SimpleDateFormat("HH:mm",Locale.getDefault()).format(new Date(seconds*1000L));}
}
